Validation failed due to manually inserted value - html

Value of filename is being manually inserted using this
<input type="file" ngf-select ng-model="file" name="file" id="file" onchange="document.getElementById('fileName').value = this.value.split('\\').pop().split('/').pop()" required>
Filename is being injected into fileName field using the file a user chooses. Validation fails as it treats that field as still being empty until I at least insert one more character. What can I do to fix that?
This is the validation part
<p ng-show="fileNameForm.fileNameInput.$error.required && fileNameForm.fileNameInput.$touched" class="help-block">File name is required.</p>
And the actual text field
<input name="fileNameInput" class="form-control" type="text" id="fileName" ng-model="document.fileName" ng-maxlength="255" required>

on change will not be evaluated if the model is changed programmatically and not by a change to the input value
you can use $scope.$watch to detect changes on ng-model
$scope.$watch('document.fileName', function(newValue, oldValue) {
//if(newValue not valid)
// display validation error
});

Related

Input type=number Safari still allows letters with stepper

I have an input field which only allows number:
<input class="border" type="number" numeric step="0.1" inputmode="numeric" digitOnly maxlength="6" formControlName="resultInput" pattern="[0-9]+"/>
I set more parameters than needed just to check if it would work with these. Unluckily it didn't.
When I am using it on Chrome it works, but when I am using it on Safari it doesn't.
Unfortunately, many browsers will only validate the input for an input with type="number" upon form submission. In such a case, the following prompt will appear (example from Safari):
I've modified your snippet to remove any non-numeric input as it is entered. I have tested that this snippet works on the Chrome, Firefox and Safari.
<input class="border" type="number" numeric step="0.1" inputmode="numeric" digitOnly maxlength="6" formControlName="resultInput" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1').replace(/^0[^.]/, '0');" />
If you were willing to forgo the stepper, you could avoid having a single non-numerical character remove the entire input:
<input class="border" type="text" inputmode="numeric" digitOnly maxlength="6" formControlName="resultInput" oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1').replace(/^0[^.]/, '0');" />
In these snippets, we use:
oninput="this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*?)\..*/g, '$1').replace(/^0[^.]/, '0');"
to remove all characters that would result in the value in the input not matching a typical numeric form (no leading zeroes, no more than one decimal point).
Be warned: while you can use HTML, CSS and JavaScript to restrict what users enter when using your website normally (known as 'client-side validation'), it is trivial to bypass the restrictions set this way.
If you are sending this data to a server for transformation, you should not trust that this data will only be numeric and of the form you expect. You should consider this type of validation to be purely for convenience's sake rather than providing any guarantee that the server will receive valid data.
The above series of "replace" did not work for me. Since my project is in Angular, I instead created a custom form field validator. That way, an error is presented to the user on invalid input (which prevents form submission):
public static numberInputValidator(min: number, max: number): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
if (isUndefinedOrEmpty(control?.value) || control.value <= min) {
return { numberRequired: true };
} else if(control.value > max) {
return { numberTooBig: true };
}
return null;
};
}
The only related attributes on the HTML input field are: type="number" step=".01"
To use it, add the validator to your FormControl in your FormGroup:
myControlName: new FormControl<undefined | number>(undefined, numberInputValidator(0, 100))
And even though the validator takes only number inputs, it will return numberRequired if the form field contains non-numeric characters.
You can then display custom error messages as such this (right after the <input> field) if using Angular Material form fields:
<mat-error *ngIf="vm.formGroup.get('myControlName')?.errors?.numberRequired">
<p>Amount must be greater than zero</p>
</mat-error>
<mat-error *ngIf="vm.formGroup.get('myControlName')?.errors?.numberTooBig">
<p>Amount must be less than or equal to 100</p>
</mat-error>

An invalid form control with name='' is not focusable. WITHOUT ANY REQUIRED OR HIDDEN INPUTS

I'm facing the well known Chrome's "not-focusable-input" error but my situation is different from the explained in the other post I could find there.
I have this error message duplicated first on a well pointed input, this input has no required attribute:
The code:
<fieldset>
<label>Total (montaje incl.)</label>
<input type="number" id="priceFinal" name="priceFinal"> €
</fieldset>
The error:
An invalid form control with name='priceFinal' is not focusable.
While the user is filling the form this field gets its value by a js script with jquery. The user type a size in another input, the script do its maths with the size value and then put the outcome in the 'priceFinal' input with the jquery function: .val()
In the browser we can see that the input is correctly filled and no errors are displayed at that time. And with the 'novalidate' solution everything goes fine, so it couldn't be responsible for the nofocusable error, I think.
Then I got the same error with an input with no name which I didn't write and doesn't exist in my DOM:
An invalid form control with name='' is not focusable.
This is weird because the only input without name in my form is the type:submit one
<input type="submit" class="btn btn-default" value="Ver presupuesto" />
I have a few required fields but I've always checked that their are all filled when I send the form. I paste it just in case it could help:
<fieldset>
<input type="text" id="clientName" name="clientName" placeholder="Nombre y apellidos" class="cInput" required >
<input type="text" id="client_ID" name="client_ID" required placeholder="CIF / NIF / DNI" class="cInput">
</fieldset>
<fieldset>
<input type="text" id="client_add" name="client_add" placeholder="Dirección de facturación" class="addInput" required >
</fieldset>
<fieldset>
<input type="text" id="client_ph" name="client_ph" placeholder="Teléfono" class="cInput" required>
<input type="email" id="client_mail" name="client_mail" placeholder="Email" class="cInput" required>
</fieldset>
The novalidate solution clears the error but it doesn't fix it, I mean there must be a way to solve it with no hacks.
Any one have any idea of what's might going on?
Thanks
I had the same problem, and everyone was blaming to the poor hidden inputs been required, but seems like a bug having your required field inside a fieldset.
Chrome tries to focus (for some unknown reason) your fieldset instead of your required input.
This bug is present only in chrome I tested in version 43.0.2357.124 m.
Doesn't happen in firefox.
Example (very simple).
<form>
<fieldset name="mybug">
<select required="required" name="hola">
<option value=''>option 1</option>
</select>
<input type="submit" name="submit" value="send" />
</fieldset>
</form>
An invalid form control with name='mybug' is not focusable.
The bug is hard to spot because usually fieldsets don't have a name so name='' is a WTF! but slice piece by piece the form until I found the culprid.
If you get your required input from the fieldset the error is gone.
<form>
<select required="required" name="hola">
<option value=''>option 1</option>
</select>
<fieldset name="mybug">
<input type="submit" name="submit" value="send" />
</fieldset>
</form>
I would report it but I don't know where is the chrome community for bugs.
Thanks to this post, I saw that my problem also rested with Chrome trying to focus on my fieldsets, instead of the input field.
To get a better response from the console:
Assign every DOM element a new name
Set every input & select style.display to 'block'
Changed the type of input[type="hidden"] elements to 'text'
function cleanInputs(){
var inputs = document.getElementsByTagName( 'input' ),
selects = document.getElementsByTagName( 'select' ),
all = document.getElementsByTagName( '*' );
for( var i=0, x=all.length; i<x; i++ ){
all[i].setAttribute( 'name', i + '_test' );
}
for( var i=0, x=selects.length; i<x; i++ ){
selects[i].style.display = 'block';
}
for( var i=0, x=inputs.length; i<x; i++ ){
if( inputs[i].getAttribute( 'type' ) === 'hidden' ){
inputs[i].setAttribute( 'type', 'text' );
}
inputs[i].style.display = 'block';
}
return true;
}
In the console, I ran cleanInputs() and then submitted the form.
The result, from the console, was:
An invalid form control with name='28_test' is not focusable.
An invalid form control with name='103_test' is not focusable.
Then, switching over to the Web Developer "Elements" view, I was able to find "28_test" and "103_test" (both fieldsets) -- confirming that my problem was a required input field, nested inside a fieldset.
While I was writting the question I realized one thing: the value the script was putting into the 'priceFinal' field sometimes was a decimal number.
In this case the solution was to write the step attribute for this input:
... step="any" ...
Step on w3s
So this 'nofocusable' bug is not only a required and hidden fields issue, it's also generated by format conflicts.
Nach gave me the best pointer... (y) I also had a input type="number" with step="0.1" and the console shows me this error while validating: An invalid form control with name='' is not focusable.
remove the step="0.1" on the element and now the form can be validated
I had the same issue so I removed required="required" from the troublesome fields.
If you get the error when jQuery function is executed, try to put "return false" on your function, or function(e) { e.preventDefault(); ... }
i had this issue once. to fix it, add
novalidate
as an attribute to the form. e.g
<form action="" novalidate>
....
</form>
In my case, the input element did not have a required attribute but it was hidden. and the problem was while it was hidden, it had a value in it. I guess if an input field is hidden it shouldn't have a value too, aside required attribute.
When I remove the value through my javascript code, everything works fine.
Element is hidden, No required Attribute, No value. Worked
Here is the solution....
<form>
<input type="text" ng-show="displayCondition" ng-required="displayCondition"/>
</form>
Many people do not realize that passing false into ng-required disables the directive.

jQueryValidate - Empty Password not stopping form

I have a simple form using jQueryValidate:
$("#frmMain").validate();
Leaving an empty Email will cause the validation to show and the form to stop, the password can strangely be left blank and the form submits.
What changes do I need to ensure the form doesn't submit when the password is empty, like the email does now:
<form action="Login" id="frmMain" method="post" name="frmMain" role="form">
<input class="input-validation-error form-control" data-msg-email="The Email field is not a valid e-mail address." data-msg-required="The Email field is required." data-rule-email="true" data-rule-required="true" id="Email" name="Email" type="email" />
<input autocomplete="off" class="input-validation-error form-control" data-val="true" data-val-length="The new password must be at least 8 characters long" data-val-length-max="15" data-val-length-min="8" data-val-required="Password is required" id="Password" name="Password" type="password" />
Note, I set the default values for the validator:
submitHandler: function (form) {
if ($(form).valid()) {
form.submit();
}
}
The code here is redundant and superfluous...
submitHandler: function (form) {
if ($(form).valid()) {
form.submit();
}
}
You don't need if form.valid() because the submitHandler only fires on a valid form. (Your conditional if will never be false).
You don't need form.submit() because this is the default behavior when the form is valid. (the form action will fire)
That leaves nothing... so you don't need to specify a custom submitHandler for this case at all. (it can be left out entirely as I did in jsFiddle below)
Quote OP:
"... the password can strangely be left blank and the form submits. What changes do I need to ensure the form doesn't submit when the password is empty"
What is so strange when no rule was specified that mandates the field be filled? If you need to stop submit when the password is blank, you need the required rule. Just compare the attributes from the email field to the password field and you'll see that data-rule-required is where the required rule is specified...
data-rule-required="true"
Add this attribute to the password field and now the field must be filled out.
Working DEMO: http://jsfiddle.net/tv49y/

How can I change or remove HTML form validation default error messages?

For example I have a textfield. The field is mandatory, only numbers are required and length of value must be 10. When I try to submit form with value which length is 5, the default error message appears: Please match the requested format
<input type="text" required="" pattern="[0-9]{10}" value="">
How can I change HTML form validation errors default messages?
If the 1st point can be done, is there a way to create some property files and set in that files custom error messages?
This is the JavaScript solution:
<input type="text"
pattern="[a-zA-Z]+"
oninvalid="setCustomValidity('Please enter Alphabets.')"
onchange="try{setCustomValidity('')}catch(e){}" />
The "onchange" event needs when you set an invalid input data, then correct the input and send the form again.
I've tested it on Firefox, Chrome and Safari.
But for Modern Browsers:
Modern browsers didn't need any JavaScript for validation.
Just do it like this:
<input type="text"
pattern="[a-zA-Z]+"
title="Please enter Alphabets."
required="" />
When using pattern= it will display whatever you put in the title attrib, so no JS required just do:
<input type="text" required="" pattern="[0-9]{10}" value="" title="This is an error message" />
<input type="text" pattern="[a-zA-Z]+"
oninvalid="setCustomValidity('Plz enter on Alphabets ')" />
I found this code in another post.
HTML:
<input type="text" pattern="[0-9]{10}" oninvalid="InvalidMsg(this);" name="email" oninput="InvalidMsg(this);" />
JAVASCRIPT :
function InvalidMsg(textbox) {
if(textbox.validity.patternMismatch){
textbox.setCustomValidity('please enter 10 numeric value.');
}
else {
textbox.setCustomValidity('');
}
return true;
}
Fiddle Demo
To prevent the browser validation message from appearing in your document, with jQuery:
$('input, select, textarea').on("invalid", function(e) {
e.preventDefault();
});
you can remove this alert by doing following:
<input type="text" pattern="[a-zA-Z]+"
oninvalid="setCustomValidity(' ')"
/>
just set the custom message to one blank space
you can change them via constraint validation api: http://www.w3.org/TR/html5/constraints.html#dom-cva-setcustomvalidity
if you want an easy solution, you can rock out civem.js, Custom Input Validation Error Messages JavaScript lib
download here: https://github.com/javanto/civem.js
live demo here: http://jsfiddle.net/hleinone/njSbH/
The setCustomValidity let you change the default validation message.Here is a simple exmaple of how to use it.
var age = document.getElementById('age');
age.form.onsubmit = function () {
age.setCustomValidity("This is not a valid age.");
};
I Found a way Accidentally Now:
you can need use this: data-error:""
<input type="username" class="form-control" name="username" value=""
placeholder="the least 4 character"
data-minlength="4" data-minlength-error="the least 4 character"
data-error="This is a custom Errot Text fot patern and fill blank"
max-length="15" pattern="[A-Za-z0-9]{4,}"
title="4~15 character" required/>
I found a bug on Mahoor13 answer, it's not working in loop so I've fixed it with this correction:
HTML:
<input type="email" id="eid" name="email_field" oninput="check(this)">
Javascript:
function check(input) {
if(input.validity.typeMismatch){
input.setCustomValidity("Dude '" + input.value + "' is not a valid email. Enter something nice!!");
}
else {
input.setCustomValidity("");
}
}
It will perfectly running in loop.
This is work for me in Chrome
<input type="text" name="product_title" class="form-control"
required placeholder="Product Name" value="" pattern="([A-z0-9À-ž\s]){2,}"
oninvalid="setCustomValidity('Please enter on Producut Name at least 2 characters long')" />
To set custom error message for HTML validation use,
oninvalid="this.setCustomValidity('Your custom message goes here.')"
and to remove this message when user enters valid data use,
onkeyup="setCustomValidity('')"
As you can see here:
html5 oninvalid doesn't work after fixed the input field
Is good to you put in that way, for when you fix the error disapear the warning message.
<input type="text" pattern="[a-zA-Z]+"
oninvalid="this.setCustomValidity(this.willValidate?'':'your custom message')" />

How can I make an input field read only but still have it send data back to a form?

I have an input field:
<input cid="Topic_Created" name="Topic.Created" size="25" type="text" value="6/5/2011 8:22:45 AM" />
I want the field to display on my form but don't want the user to be able to edit the field. When the user clicks submit I want the form value to be sent back to the server.
Is this possible. I tried different combinations of disabled = "disabled", readonly = "readonly". Seems I always get nothing sent back for the field.
Adding a hidden field with the same name will sends the data when the form is submitted.
<input type="hidden" name="my_name" value="blablabla" />
<input type="text" name="my_name" value="blablabla" disabled="disabled" />
With Chrome browser on Windows 10 just having name="your_name" and the readonly attributes works fine: client cannot change a value, but it is sent to the server.
On the assumption you're using a script to create the form, I'd suggest using <input type="hidden" /> which will submit the variable with the form, but also use a regular <input type="text" readonly="readonly" /> to show the variable to the user. This won't submit the value, obviously, but will make it visible (while the hidden input will submit the value, but not show the value).
You could also do this with JavaScript:
var theForm = document.getElementsByTagName('form')[0];
var inputs = document.getElementsByTagName('input');
for (i=0; i<inputs.length; i++){
if(inputs[i].type == 'hidden'){
var newInput = document.createElement('input');
newInput.type = 'text';
newInput.setAttribute('disabled');
newInput.value = inputs[i].value;
theForm.appendChild(newInput);
}
}
Clumsy JS Fiddle demo.
alternatively u can make a little manipulation with javascript, remove the disabled property before form submitted
<form action="target.php" method="post">
<input type="text" id="anu" name="anu" value="data anu" disabled="disabled" />
<button onclick="document.getElementById('anu').disabled=''">send</button>
<script type="text/javascript">
function myFn(event) {
event.stopPropagation(); event.preventDefault();
}
</script>
<input onkeydown="myFn(event)" >
You can add 'readonly'='true' in the input element. With this the user cant edit and also send the value back to the server.
<input cid="Topic_Created" name="Topic.Created" size="25" type="text" value="6/5/2011 8:22:45 AM" readonly='true' />
You should consider using input type="hidden" when submitting read-only fields. Otherwise, if you still need the value of input field to be visible, you should create another input (type=text) with a different name.
<input cid="Topic_Created" name="Topic.Created" type="hidden" value="6/5/2011 8:22:45 AM" />
<!--This is visible: -->
<input cid="Topic_Created" name="doesntmatter" size="25" type="text" value="6/5/2011 8:22:45 AM" />