changing the language of error message in required field in html5 contact form - forms

I am trying to change the language of the error message in the html5 form field.
I have this code:
<input type="text" name="company_name" oninvalid="setCustomValidity('Lütfen işaretli yerleri doldurunuz')" required />
but on submit, even the field is not blank, I still get the error message.
I tried with <input type="text" name="company_name" setCustomValidity('Lütfen işaretli yerleri doldurunuz') required />
but then the english message is displayed. Anyone know how can I display the error message on other language?
Regards,Zoran

setCustomValidity's purpose is not just to set the validation message, it itself marks the field as invalid. It allows you to write custom validation checks which aren't natively supported.
You have two possible ways to set a custom message, an easy one that does not involve Javascript and one that does.
The easiest way is to simply use the title attribute on the input element - its content is displayed together with the standard browser message.
<input type="text" required title="Lütfen işaretli yerleri doldurunuz" />
If you want only your custom message to be displayed, a bit of Javascript is required. I have provided both examples for you in this fiddle.

your forget this in oninvalid, change your code with this:
oninvalid="this.setCustomValidity('Lütfen işaretli yerleri doldurunuz')"
<form><input type="text" name="company_name" oninvalid="this.setCustomValidity('Lütfen işaretli yerleri doldurunuz')" required /><input type="submit">
</form>

HTML:
<form id="myform">
<input id="email" oninvalid="InvalidMsg(this);" name="email" oninput="InvalidMsg(this);" type="email" required="required" />
<input type="submit" />
</form>
JAVASCRIPT :
function InvalidMsg(textbox) {
if (textbox.value == '') {
textbox.setCustomValidity('Lütfen işaretli yerleri doldurunuz');
}
else if (textbox.validity.typeMismatch){
textbox.setCustomValidity('Lütfen işaretli yere geçerli bir email adresi yazınız.');
}
else {
textbox.setCustomValidity('');
}
return true;
}
Demo :
http://jsfiddle.net/patelriki13/Sqq8e/4

This work for me.
<input oninvalid="this.setCustomValidity('custom text on invalid')" onchange="this.setCustomValidity('')" required>
onchange is a must!

I know this is an old post but i want to share my experience.
HTML:
<input type="text" placeholder="Username or E-Mail" required data-required-message="E-Mail or Username is Required!">
Javascript (jQuery):
$('input[required]').on('invalid', function() {
this.setCustomValidity($(this).data("required-message"));
});
This is a very simple sample. I hope this can help to anyone.

TLDR: Usually, you don't need to change the validation message but if you do use this:
<input
oninvalid="this.setCustomValidity('Your custom message / 您的自定义信息')"
oninput="this.setCustomValidity('')"
required="required"
type="text"
name="text"
>
The validation messages are coming from your browser and if your browser is in English the message will be in English, if the browser is in French the message will be in French and so on.
If you an input for which the default validation messages doesn't work for you, the easiest solution is to provide your custom message to setCustomValidity as a parameter.
...
oninvalid="this.setCustomValidity('Your custom message / 您的自定义信息')"
...
This is a native input's method which overwrites the default message. But now we have one problem, once the validation is triggered, the message will keep showing while the user is typing. So to stop the message from showing you can set the validity message to empty string using the oninput attribute.
...
oninput="this.setCustomValidity('')"
...

//Dynamic custome validation on all fields
//add validate-msg attr to all inputs
//add this js code
$("form :input").each(function(){
var input = $(this);
var msg = input.attr('validate-msg');
input.on('change invalid input', function(){
input[0].setCustomValidity('');
if(!(input[0].validity.tooLong || input[0].validity.tooShort)){
if (! input[0].validity.valid) {
input[0].setCustomValidity(msg);
}
}
});
});

<input type="text" id="inputName" placeholder="Enter name" required oninvalid="this.setCustomValidity('Your Message')" oninput="this.setCustomValidity('') />
this can help you even more better, Fast, Convenient & Easiest.

For the lost souls who are seeking a way to fully localize their error messages, see the snippet below. In short, you have to switch over the properties of event.target.validity and override the corresponding error message using event.target.setCustomValidity(message). If you just care about the empty field case as OP, just consider the case of valueMissing.
Note that the handler is passed in the React way, but other answers already covered how to do it in vanilla JS.
For the meaning of each validity state and how to implement customized error messages, see MDN: Validating forms using JavaScript.
const handleInvalidForm = (event) => {
const { patternMismatch,
tooLong,
tooShort,
rangeOverflow,
rangeUnderflow,
typeMismatch,
valid,
valueMissing } = event.target.validity;
if (patternMismatch)
event.target.setCustomValidity('...');
else if (tooLong)
event.target.setCustomValidity('...');
else if (tooShort)
event.target.setCustomValidity('...');
else if (rangeOverflow)
event.target.setCustomValidity('...');
else if (rangeUnderflow)
event.target.setCustomValidity('...');
else if (typeMismatch)
event.target.setCustomValidity('...');
else if (valid)
event.target.setCustomValidity('...');
else if (valueMissing)
event.target.setCustomValidity('...');
}
// ...
<form onSubmit={handleFormSubmit}
onInvalid={handleInvalidForm}
>
{emailTextField}
{passwordTextField}
{signInButton}
</form>

<input type="text" id="inputName" placeholder="Enter name" required oninvalid="this.setCustomValidity('Please Enter your first name')" >
this can help you even more better, Fast, Convenient & Easiest.

Do it using JS. Grab the class of the error message, and change it's content for whereever it appears.
var myClasses = document.getElementsByClassName("wpcf7-not-valid-tip");
for (var i = 0; i < myClasses.length; i++) {
myClasses[i].innerHTML = "Bitte füllen Sie das Pflichtfeld aus.";
}

<form>
<input
type="text"
name="company_name"
oninvalid="this.setCustomValidity('Lütfen işaretli yerleri doldurunuz')"
required
/><input type="submit" />
</form>

Related

How do I get the form submit alert to cancel form action?

I have a javascript function that checks if someone entered their email:
function formValidate(){
form1 = document.forms['_register1'];
if (form1.elements['email'].value == 'Type Your Email Address Here')
{
alert('Please enter your email address.');
form1.elements['email'].focus();
return false;
}
}
Here is the form html:
<form method="post" enctype="multipart/form-data" name="_register1" id="_register" action="signup.php" >
<input type="text" class="field" value="Type Your Email Address Here" name="email" title="Type Your Email Address Here" />
<input type="submit" class="button button-signup" value="SIGN UP!" onclick="formValidate();" />
If the user has not entered an email address, I want the javascript alert to popup and once the user presses ok, I want the page to stay the same. I don't want the action="signup.php" to happen until the email is valid. This seems like it should be simple but I've looked all over the internet and can't find a solution.
Thanks.
http://www.html-form-guide.com/php-form/php-login-form.html
this might be what you're looking for.
I finally figured out the answer. The key is to use the javascript submit() function. Rather than use an input type submit, I use just a regular button. Then, after javascript validates the form and the form has the proper data, I used the submit function. Here is my code below. If anyone is curious, feel free to ask me about it.
function formValidate(){
//define form1 as registration form
form1 = document.forms['_register1'];
var submission = true;
//make sure email address is not blank
if (form1.elements['email'].value == 'Type Your Email Address Here') {
alert('Please enter your email address.');
form1.elements['email'].focus();
var submission = false;
}
//submit form if data is good
if(submission != false){
form1.submit();
}
}
And here is the html:
<input type="text" value="Type Your Email Address Here" name="email" title="Enter email" />
<input type="button" value="SIGN UP!" onclick="formValidation();" />

Adding an extra relative value to an input value field

I'm currently creating a form that is very similar to the following code.
<form name="test" action="/go/test" method="post">
<input type=hidden name="hotspot_url" value="http://www.test.com/">
<input name="cky" value="<%write(cky);%>" type="hidden">
<input name="accept" value="Accept" type="hidden">
<input name="saccept" size="20" value="I Accept" onClick="hotspot.accept.value='Accept'" type="submit">
<input name="sdisconnect" size="20" value="I Decline" onClick="hotspot.accept.value='Decline'" type="submit">
</form>
However, the new form has a text input field. What I want to achieve is that the value entered in that text field is placed, upon send, after the test.com value (location marked with xxx)
<input type=hidden name="hotspot_url" value="http://www.test.com/xxx">
I've looked around - but i can't seem to find a solution.
What would be the best way to get this done?
You can use a buttons onclick event, which is not of type submit. When onclick occurs, you can first change the value of hidden field and then submit the form.
Or if you use JQuery, you can use the following jQuery code to do something before the form is submitted:
$(function() {
$('#form').submit(function() {
// DO STUFF
return true; // return false to cancel form action
});
});
You can give both inputs an id, and do something like this:
give the form an "onsumbit= doThis()"
function doThis(){
var hiddeninput= $('#hiddeninput').val();
var input = $('#input').val();
$('#hiddeninput').val(hiddeninput+input);
return true;
}
this is very simple nothing fancy.

Trigger validation of all fields in Angular Form submit

I'm using this method: http://plnkr.co/edit/A6gvyoXbBd2kfToPmiiA?p=preview to only validate fields on blur. This works fine, but I would also like to validate them (and thus show the errors for those fields if any) when the user clicks the 'submit' button (not a real submit but a data-ng-click call to a function)
Is there some way to trigger validation on all the fields again when clicking that button?
What worked for me was using the $setSubmitted function, which first shows up in the angular docs in version 1.3.20.
In the click event where I wanted to trigger the validation, I did the following:
vm.triggerSubmit = function() {
vm.homeForm.$setSubmitted();
...
}
That was all it took for me. According to the docs it "Sets the form to its submitted state." It's mentioned here.
I know, it's a tad bit too late to answer, but all you need to do is, force all forms dirty. Take a look at the following snippet:
angular.forEach($scope.myForm.$error.required, function(field) {
field.$setDirty();
});
and then you can check if your form is valid using:
if($scope.myForm.$valid) {
//Do something
}
and finally, I guess, you would want to change your route if everything looks good:
$location.path('/somePath');
Edit: form won't register itself on the scope until submit event is trigger. Just use ng-submit directive to call a function, and wrap the above in that function, and it should work.
In case someone comes back to this later... None of the above worked for me. So I dug down into the guts of angular form validation and found the function they call to execute validators on a given field. This property is conveniently called $validate.
If you have a named form myForm, you can programmatically call myForm.my_field.$validate() to execute field validation. For example:
<div ng-form name="myForm">
<input required name="my_field" type="text" ng-blur="myForm.my_field.$validate()">
</div>
Note that calling $validate has implications for your model. From the angular docs for ngModelCtrl.$validate:
Runs each of the registered validators (first synchronous validators and then asynchronous validators). If the validity changes to invalid, the model will be set to undefined, unless ngModelOptions.allowInvalid is true. If the validity changes to valid, it will set the model to the last available valid $modelValue, i.e. either the last parsed value or the last value set from the scope.
So if you're planning on doing something with the invalid model value (like popping a message telling them so), then you need to make sure allowInvalid is set to true for your model.
You can use Angular-Validator to do what you want. It's stupid simple to use.
It will:
Only validate the fields on $dirty or on submit
Prevent the form from being submitted if it is invalid
Show custom error message after the field is $dirty or the form is submitted
See the demo
Example
<form angular-validator
angular-validator-submit="myFunction(myBeautifulForm)"
name="myBeautifulForm">
<!-- form fields here -->
<button type="submit">Submit</button>
</form>
If the field does not pass the validator then the user will not be able to submit the form.
Check out angular-validator use cases and examples for more information.
Disclaimer: I am the author of Angular-Validator
Well, the angular way would be to let it handle validation, - since it does at every model change - and only show the result to the user, when you want.
In this case you decide when to show the errors, you just have to set a flag:
http://plnkr.co/edit/0NNCpQKhbLTYMZaxMQ9l?p=preview
As far as I know there is a issue filed to angular to let us have more advanced form control. Since it is not solved i would use this instead of reinventing all the existing validation methods.
edit: But if you insist on your way, here is your modified fiddle with validation before submit. http://plnkr.co/edit/Xfr7X6JXPhY9lFL3hnOw?p=preview
The controller broadcast an event when the button is clicked, and the directive does the validation magic.
One approach is to force all attributes to be dirty. You can do that in each controller, but it gets very messy. It would be better to have a general solution.
The easiest way I could think of was to use a directive
it will handle the form submit attribute
it iterates through all form fields and marks pristine fields dirty
it checks if the form is valid before calling the submit function
Here is the directive
myModule.directive('submit', function() {
return {
restrict: 'A',
link: function(scope, formElement, attrs) {
var form;
form = scope[attrs.name];
return formElement.bind('submit', function() {
angular.forEach(form, function(field, name) {
if (typeof name === 'string' && !name.match('^[\$]')) {
if (field.$pristine) {
return field.$setViewValue(field.$value);
}
}
});
if (form.$valid) {
return scope.$apply(attrs.submit);
}
});
}
};
});
And update your form html, for example:
<form ng-submit='justDoIt()'>
becomes:
<form name='myForm' novalidate submit='justDoIt()'>
See a full example here: http://plunker.co/edit/QVbisEK2WEbORTAWL7Gu?p=preview
Here is my global function for showing the form error messages.
function show_validation_erros(form_error_object) {
angular.forEach(form_error_object, function (objArrayFields, errorName) {
angular.forEach(objArrayFields, function (objArrayField, key) {
objArrayField.$setDirty();
});
});
};
And in my any controllers,
if ($scope.form_add_sale.$invalid) {
$scope.global.show_validation_erros($scope.form_add_sale.$error);
}
Based on Thilak's answer I was able to come up with this solution...
Since my form fields only show validation messages if a field is invalid, and has been touched by the user I was able to use this code triggered by a button to show my invalid fields:
// Show/trigger any validation errors for this step
angular.forEach(vm.rfiForm.stepTwo.$error, function(error) {
angular.forEach(error, function(field) {
field.$setTouched();
});
});
// Prevent user from going to next step if current step is invalid
if (!vm.rfiForm.stepTwo.$valid) {
isValid = false;
}
<!-- form field -->
<div class="form-group" ng-class="{ 'has-error': rfi.rfiForm.stepTwo.Parent_Suffix__c.$touched && rfi.rfiForm.stepTwo.Parent_Suffix__c.$invalid }">
<!-- field label -->
<label class="control-label">Suffix</label>
<!-- end field label -->
<!-- field input -->
<select name="Parent_Suffix__c" class="form-control"
ng-options="item.value as item.label for item in rfi.contact.Parent_Suffixes"
ng-model="rfi.contact.Parent_Suffix__c" />
<!-- end field input -->
<!-- field help -->
<span class="help-block" ng-messages="rfi.rfiForm.stepTwo.Parent_Suffix__c.$error" ng-show="rfi.rfiForm.stepTwo.Parent_Suffix__c.$touched">
<span ng-message="required">this field is required</span>
</span>
<!-- end field help -->
</div>
<!-- end form field -->
Note: I know this is a hack, but it was useful for Angular 1.2 and earlier that didn't provide a simple mechanism.
The validation kicks in on the change event, so some things like changing the values programmatically won't trigger it. But triggering the change event will trigger the validation. For example, with jQuery:
$('#formField1, #formField2').trigger('change');
I like the this approach in handling validation on button click.
There is no need to invoke anything from controller,
it's all handled with a directive.
on github
You can try this:
// The controller
$scope.submitForm = function(form){
//Force the field validation
angular.forEach(form, function(obj){
if(angular.isObject(obj) && angular.isDefined(obj.$setDirty))
{
obj.$setDirty();
}
})
if (form.$valid){
$scope.myResource.$save(function(data){
//....
});
}
}
<!-- FORM -->
<form name="myForm" role="form" novalidate="novalidate">
<!-- FORM GROUP to field 1 -->
<div class="form-group" ng-class="{ 'has-error' : myForm.field1.$invalid && myForm.field1.$dirty }">
<label for="field1">My field 1</label>
<span class="nullable">
<select name="field1" ng-model="myresource.field1" ng-options="list.id as list.name for list in listofall"
class="form-control input-sm" required>
<option value="">Select One</option>
</select>
</span>
<div ng-if="myForm.field1.$dirty" ng-messages="myForm.field1.$error" ng-messages-include="mymessages"></div>
</div>
<!-- FORM GROUP to field 2 -->
<div class="form-group" ng-class="{ 'has-error' : myForm.field2.$invalid && myForm.field2.$dirty }">
<label class="control-label labelsmall" for="field2">field2</label>
<input name="field2" min="1" placeholder="" ng-model="myresource.field2" type="number"
class="form-control input-sm" required>
<div ng-if="myForm.field2.$dirty" ng-messages="myForm.field2.$error" ng-messages-include="mymessages"></div>
</div>
</form>
<!-- ... -->
<button type="submit" ng-click="submitForm(myForm)">Send</button>
I done something following to make it work.
<form name="form" name="plantRegistrationForm">
<div ng-class="{ 'has-error': (form.$submitted || form.headerName.$touched) && form.headerName.$invalid }">
<div class="col-md-3">
<div class="label-color">HEADER NAME
<span class="red"><strong>*</strong></span></div>
</div>
<div class="col-md-9">
<input type="text" name="headerName" id="headerName"
ng-model="header.headerName"
maxlength="100"
class="form-control" required>
<div ng-show="form.$submitted || form.headerName.$touched">
<span ng-show="form.headerName.$invalid"
class="label-color validation-message">Header Name is required</span>
</div>
</div>
</div>
<button ng-click="addHeader(form, header)"
type="button"
class="btn btn-default pull-right">Add Header
</button>
</form>
In your controller you can do;
addHeader(form, header){
let self = this;
form.$submitted = true;
...
}
You need some css as well;
.label-color {
color: $gray-color;
}
.has-error {
.label-color {
color: rgb(221, 25, 29);
}
.select2-choice.ui-select-match.select2-default {
border-color: #e84e40;
}
}
.validation-message {
font-size: 0.875em;
}
.max-width {
width: 100%;
min-width: 100%;
}
To validate all fields of my form when I want, I do a validation on each field of $$controls like this :
angular.forEach($scope.myform.$$controls, function (field) {
field.$validate();
});

HTML required readonly input in form

I'm making a form. And on one input tag is an OnClick event handler, which is opening a popup, where you can choose some stuff, and then it autofills the input tag.
That input tag is also readonly, so only right data will be entered.
This is the code of the input tag:
<input type="text" name="formAfterRederict" id="formAfterRederict" size="50" required readonly="readonly" OnClick="choose_le_page();" />
But the required attribute isn't working in Chrome. But the field is required.
Does anybody know how I can make it work?
I had same requirement as yours and I figured out an easy way to do this.
If you want a "readonly" field to be "required" also (which is not supported by basic HTML), and you feel too lazy to add custom validation, then just make the field read only using jQuery this way:
IMPROVED
form the suggestions in comments
<input type="text" class="readonly" autocomplete="off" required />
<script>
$(".readonly").on('keydown paste focus mousedown', function(e){
if(e.keyCode != 9) // ignore tab
e.preventDefault();
});
</script>
Credits: #Ed Bayiates, #Anton Shchyrov, #appel, #Edhrendal, #Peter Lenjo
ORIGINAL
<input type="text" class="readonly" required />
<script>
$(".readonly").keydown(function(e){
e.preventDefault();
});
</script>
readonly fields cannot have the required attribute, as it's generally assumed that they will already hold some value.
Remove readonly and use function
<input type="text" name="name" id="id" required onkeypress="return false;" />
It works as you want.
Required and readonly don't work together.
But readonly can be replaced with following construction:
<input type="text"
onkeydown="return false;"
style="caret-color: transparent !important;"
required>
1) onkeydown will stop manipulation with data
2) style="caret-color: transparent !important;" will hide cursor.
3) you can add style="pointer-events: none;" if you don't have any events on your input, but it was not my case, because I used a Month Picker. My Month picker is showing a dialog on click.
This is by design. According to the official HTML5 standard drafts, "if the readonly attribute is specified on an input element, the element is barred from constraint validation." (E.g. its values won't be checked.)
Yes, there is a workaround for this issue. I found it from https://codepen.io/fxm90/pen/zGogwV site.
Solution is as follows.
HTML File
<form>
<input type="text" value="" required data-readonly />
<input type="submit" value="Submit" />
</form>
CSS File
input[data-readonly] {
pointer-events: none;
}
If anyone wants to do it only from html, This works for me.
<input type="text" onkeydown="event.preventDefault()" required />
I think this should help.
<form onSubmit="return checkIfInputHasVal()">
<input type="text" name="formAfterRederict" id="formAfterRederict" size="50" required readonly="readonly" OnClick="choose_le_page();" />
</form>
<script>
function checkIfInputHasVal(){
if($("#formAfterRederict").val==""){
alert("formAfterRederict should have a value");
return false;
}
}
</script>
You can do this for your template:
<input required onfocus="unselect($event)" class="disabled">
And this for your js:
unselect(event){
event.preventDefault();
event.currentTarget.blur();
}
For a user the input will be disabled and required at the same time, providing you have a css-class for disabled input.
Based on answer #KanakSinghal but without blocked all keys and with blocked cut event
$('.readonly').keydown(function(e) {
if (e.keyCode === 8 || e.keyCode === 46) // Backspace & del
e.preventDefault();
}).on('keypress paste cut', function(e) {
e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="readonly" value="test" />
P.S. Somebody knows as cut event translate to copy event?
Required and readonly don't work together.
Although you can make two inputs like this:
<input id="One" readonly />
<input id="Two" required style="display: none" /> //invisible
And change the value Two to the value that´s inside the input One.
I have the same problem, and finally I use this solution (with jQuery):
form.find(':input[required][readonly]').filter(function(){ return this.value === '';})
In addition to the form.checkValidity(), I test the length of the above search somehow this way:
let fcnt = $(form)
.find(':input[required][readonly]')
.filter(function() { return this.value === '';})
.length;
if (form.checkValidity() && !fcnt) {
form.submit();
}
function validateForm() {
var x = document.forms["myForm"]["test2"].value;
if (x == "") {
alert("Name missing!!");
return false;
}
}
<form class="form-horizontal" onsubmit="return validateForm()" name="myForm" action="" method="POST">
<input type="text" name="test1">
<input type="text" disabled name="test2">
<button type="submit">Submit</button>
</form>

JSP - check form submission

Let say I have a simple form with no required fields:
<form action="index.jsp" method="post">
<input type="text" name="firstName" />
<input type="text" name="lastName" />
<input type="text" name="email" />
<input type="submit" value="submit" />
</form>
I want to check if the form was submitted by checking the submit parameter (because it's always present). In PHP I can do a simple
if ( $_POST['submit'] )
but the request.getParameter("submit") doesn't seem to work.
So what's the best way to check if a form was submitted?
You need to give the input element a name. It's the element's name which get sent as request parameter name.
<input type="submit" name="submit" value="submit" />
Then you can check it as follows:
if (request.getParameter("submit") != null) {
// ...
}
You perhaps also want to check if "POST".equalsIgnoreCase(request.getMethod()) is also true.
if ("POST".equalsIgnoreCase(request.getMethod()) && request.getParameter("submit") != null) {
// ...
}
Better, however, would be to use a servlet and do the job in doPost() method.
You can try this way:-
if ("POST".equalsIgnoreCase(request.getMethod())) {
// Form was submitted.
} else {
// It may be a GET request.
}