jQueryValidate - Empty Password not stopping form - html

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/

Related

HTML5 Input Required Validation fails on Submit when javascript sets the value

Basically, I have two input controls a textbox and a checkbox. What I want to happen is when the checkbox is clicked, I want to set the value of the input. The javascript I have sets the default value however when I submit, the form fails validation for the input text to be required even though the text input has the value.
function NoLienHolder() {
var lh = document.getElementById('vehicleLienHolder');
if (lh != null) {
lh.value = "NONE";
}
}
<input name="vehicleLienHolder" id="vehicleLienHolder" required="required" placeholder="Enter Lien Holder" oninvalid="this.setCustomValidity('Please enter the Lien Holder or select no lien holder.')"
oninput="this.setCustomValidity('')" /><input type="checkbox" title="No Lien Holder" onclick="NoLienHolder()" name="NoLienHolderCheckBox" id="NoLienHolderCheckBox" />No Lien Holder
This is the code you have,
function NoLienHolder() {
var lh = document.getElementById('vehicleLienHolder');
if (lh != null) {
lh.value = "NONE";
}
}
<form>
<input name="vehicleLienHolder" id="vehicleLienHolder" required="required" placeholder="Enter Lien Holder" oninvalid="this.setCustomValidity('Please enter the Lien Holder or select no lien holder.')" oninput="this.setCustomValidity('')" />
<input type="checkbox" title="No Lien Holder" onclick="NoLienHolder()" name="NoLienHolderCheckBox" id="NoLienHolderCheckBox" />No Lien Holder
<input type="submit" value="Submit">
</form>
When I ran it, I cannot reproduce the problem (it passes the validation normally), but I could see a few issues. I have modified you code to produce what I think might be a better solution.
var original = "";
function NoLienHolder() {
var lh = document.getElementById('vehicleLienHolder');
var checkbox = document.getElementById("NoLienHolderCheckBox");
if (checkbox.checked) {
original = lh.value;
document.getElementById('status').innerHTML = "Uncheck it to restore its original value";
lh.value = "NONE";
lh.setAttribute("disabled", "disabled");
lh.removeAttribute("required");
} else {
lh.value = original;
document.getElementById('status').innerHTML = "Check the Checkbox if there is no holder";
lh.setAttribute("required", "required");
lh.removeAttribute("disabled");
}
}
<form>
<input name="vehicleLienHolder" id="vehicleLienHolder" required="required" placeholder="Enter Lien Holder" oninvalid="this.setCustomValidity('Please enter the Lien Holder or select no lien holder.')" oninput="this.setCustomValidity('')" /> <input type="checkbox"
title="No Lien Holder" onclick="NoLienHolder()" name="NoLienHolderCheckBox" id="NoLienHolderCheckBox" />No Lien Holder
<input type="submit" value="Submit">
<span id="status">Check the Checkbox if there is no holder</span>
</form>
If you run it, fill in the input field manually, and submit, it will work like normal. If you don't fill in and don't check the box, the required validation will still come into effect. If you don't fill it and check the box, the text will become "NONE", and if the problem reemerges, then it will still submit, and the backend can process that.
In your original answer, you checked if the input field is empty before setting it to NONE, but if the user filled something in, and then checked the check box, what will happen? It would submit, but instead of getting NONE, you would get the user's input instead, although the checkbox is checked. So the best way is probably to save the user value, and restore it upon unchecking.
First of all, you probably want to check if the user clicked on the checkbox to check it or to uncheck it, because your script would set it the text field to "NONE" even if the user checked the checkbox, changed his mind, changed the text, and clicked on it to uncheck. Additionally, lh != null will not work, because lh is the element, not its value. You need to access its value attribute. Additionally, you might want to consider removing the required attribute from the element, setting it to empty, and disabling it when the user checks it. This prevents any issues if the user manually inputs "NONE" in the field but leaves the input box unchecked. After all, your request would send the state of the check box as well.

Validation failed due to manually inserted value

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
});

How to add default values to input fields in Thymeleaf

I am programming in Spring and using Thymeleaf as my view, and am trying to create a form where users can update their profile. I have a profile page which lists the user's information (first name, last name, address, etc), and there is a link which says "edit profile". When that link is clicked it takes them to a form where they can edit their profile. The form consists of text fields that they can input, just like your standard registration form.
Everything works fine, but my question is, when that link is clicked, how do I add the user's information to the input fields so that it is already present, and that they only modify what they want to change instead of having to re-enter all the fields.
This should behave just like a standard "edit profile" page.
Here is a segment of my edit_profile.html page:
First Name:
Here is the view controller method that returns edit_profile.html page:
#RequestMapping(value = "/edit", method = RequestMethod.GET)
public String getEditProfilePage(Model model) {
model.addAttribute("currentUser", currentUser);
System.out.println("current user firstname: " + currentUser.getFirstname());
model.addAttribute("user", new User());
return "edit_profile";
}
currentUser.getFirstname() prints out the expected value, but I'm getting blank input values in the form.
Thanks.
Solved the problem by removing th:field altogether and instead using th:value to store the default value, and html name and id for the model's field. So name and id is acting like th:field.
I'm slightly confused, you're adding currentUser and a new'd user object to the model map.
But, if currentUser is the target object, you'd just do:
<input type="text" name="firstname" value="James" th:value="${currentUser.firstname}" />
From the documentation:
http://www.thymeleaf.org/doc/tutorials/2.1/usingthymeleaf.html
I did not have a form with input elements but only a button that should call a specific Spring Controller method and submit an ID of an animal in a list (so I had a list of anmials already showing on my page). I struggled some time to figure out how to submit this id in the form. Here is my solution:
So I started having a form with just one input field (that I would change to a hidden field in the end). In this case of course the id would be empty after submitting the form.
<form action="#" th:action="#{/greeting}" th:object="${animal}" method="post">
<p>Id: <input type="text" th:field="*{id}" /></p>
<p><input type="submit" value="Submit" /> </p>
</form>
The following did not throw an error but neither did it submit the animalIAlreadyShownOnPage's ID.
<form action="#" th:action="#{/greeting}" th:object="${animal}" method="post">
<p>Id: <input type="text" th:value="${animalIAlreadyShownOnPage.id}" /></p>
<p><input type="submit" value="Submit" /> </p>
</form>
In another post user's recommended the "th:attr" attribute, but it didn't work either.
This finally worked - I simply added the name element ("id" is a String attribute in the Animal POJO).
<form action="#" th:action="#{/greeting}" th:object="${animal}" method="post">
<p>Id: <input type="text" th:value="${animalIAlreadyShownOnPage.id}" name="id" /></p>
<p><input type="submit" value="Submit" /> </p>
</form>

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.

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" />