I have the basic usage of jQuery validation:
<div class="form__group form__group--floating-labels">
<label for="registrationFirstname">{{__('Name')}} *</label>
<input type="text" name="first_name" class="input input--text fullwidth" id="registrationFirstname" required />
</div>
With the error placement:
errorElement: 'div',
errorPlacement: function (error, element) {
$(error).addClass('registration__validation-error');
var placement = $(element).data('error');
if (placement) {
$(placement).append(error);
} else {
error.insertBefore($(element).parent('.form__group--floating-labels'));
}
}
It works the way that I submit the form, if it is has the error, the message shows up, I fill up the field and the error message gets display:none.
What I would need is - remove the div with the error message completely, not just hide it. Is it possible?
Related
So I have the required error message showing the input + id that is attached to it in the html
<div class="form-validation">
<input class="modal-input" id="password" type="password" placeholder="Enter your
password">
<p>Error Message</p>
</div>
<div class="form-validation">
<input class="modal-input" id="password-confirm" type="password" placeholder="Confirm your password">
<p>Error Message</p>
</div>
So as you can see, the id's equal password and then password-confirm
Now the problem is I don't know how to create a custom text to change it from saying password-confirm to just saying password without overlapping with the id names.
Here's a picture below of what I mean
And here is the function that I wrote in order to get the "Password-confirm" to display
function getFieldName(input) {
return input.id.charAt(0).toUpperCase() + input.id.slice(1);
}
And here is my function the make sure the required fields show the error message with the getFieldName as the first word in the message
function checkRequired(inputArr) {
inputArr.forEach(function (input) {
if(input.value.trim() === '') {
showError(input, `${getFieldName(input)} is required`);
} else {
showValid(input);
}
});
}
I tried to just target the type on the input instead of the id, but I run into another issue because the input type="text" displays "Text is required" when I want it to say "Username" so I need a method to be able to create any custom word + "is required"
So essentially I could customize it to say "WHATEVER is required"
add a data tag to the html elements you are targeting. and use it do display whatever you require to display.
refer to How to store arbitrary data for some HTML tags for details.
I am currently using jQuery validation plugin to validate my form field. When a user did not enter any value on the field, an error label will be displayed, stating that "this field is required". However, the error label is displayed all the way at the left side of the browser which seems odd. Here is a screenshot of my problem, the desired outcome and my codes
Error screenshot
Desired outcome
<script>
$.validator.setDefaults({
errorClass: 'help-block',
highlight: function (element) {
$(element)
.closest('.form-group')
.addClass('has-error');
},
unhighlight: function (element) {
$(element)
.closest('.form-group')
.removeClass('has-error')
.addClass('has-success');
}
});
$('#dataForm').validate({
rules: {
accountNameInput: {
required: true
}
}
});
</script>
<form id="dataForm" role="form" class="form-horizontal">
<div class="form-group col-md-12">
<label class="control-label col-md-4" for="accountNameInput">Account name</label>
<input type="text" id="accountNameInput" name="accountNameInput" class="form-control font-bold"
maxlength="100" placeholder="Account name" value="" />
</div>
</form>
The Jquery Validation plugin docs say you can validate that at least one radio button is selected. However, when trying to do so with some extra layout, I am not getting the error highlighting.
My code looks like this.
<div class="form-group" style="margin-top:25px;">
<label for="factorSelect" class="control-label col-sm-3">Please select a recovery method</label>
<div class="input-group">
<span class="input-group-addon">
<i class="glyphicon glyphicon-envelope"></i>
</span>
<div class="form-control" style="height:auto;">
<div class="radio">
<label class="noBold-text" style="font-size: 1em">
<input id="factorSelect_email" name="factorSelect" type="radio" value="EMAIL" />Send me an email
<span class="cr"><i class="cr-icon fa fa-circle"></i></span>
</label>
</div>
<div class="radio">
<label class="noBold-text" style="font-size: 1em">
<input id="factorSelect_sms" name="factorSelect" type="radio" value="SMS" />Send an SMS to my phone
<span class="cr"><i class="cr-icon fa fa-circle"></i></span>
</label>
</div>
</div>
</div>
</div>
$("#forgotPasswordForm").validate({
rules: {
fpUsername: {
required: true,
minlength: 3
},
factorSelect: {
required: true
}
},
messages: {
fpUsername: {
required: "Please enter your username or email",
minlength: "Your username must be at least {0} characters"
},
factorSelect: {
required: "You must select a recovery method"
},
},
highlight: function (element, errorClass, validClass) {
$(element).parents(".form-group").addClass("has-error").removeClass("has-success");
},
unhighlight: function (element, errorClass, validClass) {
$(element).parents(".form-group").addClass("has-success").removeClass("has-error");
},
});
The has-error class never gets applied to the radio button group.
I reproduced the error you have in this CodePen...
The error message produced by jQuery Validate is positionned right after the invalid element... Which is the default.
Now you can position that error message elsewhere, using errorPlacement.
In this Solution, I just placed it right after the parent .input-group. I'm sure that is the puzzle piece you where looking for.
;)
errorPlacement: function(errorLabel, invalidElement){
if( $(invalidElement).is("[type='radio']") ){
var inputGroup = $(invalidElement).closest(".input-group");
inputGroup.after(errorLabel);
}
},
EDIT
With your full code, that is easier to work...
;)
The default behavior of a button in a form is to submit (Reference, see "type").
So if the type is omitted, that is what it does.
And the .validate() function isn't triggered by a button type="button".
So...
You have to prevent the default submit in order to validate first.
Then, submit if the form is valid.
This is achieved by .preventDault() and submitHandler
$("#forgotPasswordForm").on("submit",function(e){
e.preventDefault(); // Prevents the default form submit (Have to validate first!)
})
.validate({
// Skipping some lines here...
submitHandler: function(form) {
form.submit(); // Submits only if the form is valid
}
});
Updated CodePen
Ok, fixed it. Thank you for the help above with the placement of the error message. That was not my initial issue but did come up once I got the error to display at all. Your fix works great.
My primary issue turned out to be a CSS conflict with some styles that turn the radio buttons into pretty font-awesome icons. The little snippet that hides the default radio buttons causes the validation to fail as it must only look for visible fields. I set the height to zero instead and so far it seems to work.
.checkbox label input[type="checkbox"],
.radio label input[type="radio"] {
/*display: none;*/
height:0;
}
I need to validate filled inputs and on submit if all inputs are valid show load animation till next page will shown. I can check for validation one by one, but do not know how to collect them all in one. Maybe there are more simple way to check inputs validation? Also I did all validations inside inputs in code below.
Here is my inputs type which i need to validate and on success show load animation until page refresh to another page:
<form action="" method="POST" enctype="multipart/form-data" name="formz" >
<div>
<label>Name: </label>
<input type="text" onkeydown="return keyDown.call(this,event)" onchange="value = value.replace(/^\s+/,'')" pattern=".{3,20}" name="name" required>
</div>
<div>
<label>Surname: </label>
<input type="text" onkeydown="return keyDown.call(this,event)" onchange="value = value.replace(/^\s+/,'')" pattern=".{3,20}" name="surname" required>
</div>
<div>
<label>Unic Number: </label>
<input type="text" onkeydown="return keyDown.call(this,event)" onchange="value = value.replace(/^\s+/,'')" pattern=".{7,7}" maxlength='7' name="unicnumb" required />
</div>
<div>
<label>Select:</label>
<select name="select" id="select" required>
<OPTION VALUE="0" selected disabled >Select</OPTION>
<OPTION VALUE="1">Select1</OPTION>
<OPTION VALUE="2">Select2</OPTION>
</select>
</div>
<div>
<label>phone: </label>
<input type="text" name="phone" id="phone" placeholder="+XXX(XX) XXX-XX-XX" required>
</div>
<div>
<label for="epoct">E-mail</label>
<input type="email" pattern="[a-zA-Z0-9.-_]{1,}#[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}" class="form-control input-sm" name="epoct" id="epoct" required>
</div>
<button type="submit" name="button" id="button">Done</button>
</form>
This is the outline for how I've handled successive form validation with jQuery:
$(document).ready(function() {
$( "#button" ).submit(function( event ) {
if ( /* validation fails for first form element */ ) {
// stop form submission
event.preventDefault();
// display an error message
$( "#firstFormFieldId" ).append("<span>Incorrect entry</span>");
// break out of function to ensure validation continues if and only if this condition is met
return false;
}
if ( /* validation fails for second form element */ ) {
// stop form submission
event.preventDefault();
// display an error message
$( "#secondFormFieldId" ).append("<span>Incorrect entry</span>");
// break out of function to ensure validation continues if and only if this condition is met
return false;
}
if ( /* validation fails for third form element */ ) {
// stop form submission
event.preventDefault();
// display an error message
$( "#thirdFormFieldId" ).append("<span>Incorrect entry</span>");
// break out of function to ensure validation continues if and only if this condition is met
return false;
}
// ... repeat for as many form fields that need validation
// if all validation criteria are met, you can deploy loading animation here :)
/* loading animation goes here */
});
});
You can probably already imagine some variations to this template. For instance, rather than appending the <span>s, you could add empty <span>s intended to contain the error messages to your HTML. If an error message needs to be displayed, you then use jQuery to add the text of the error message to the corresponding <span>. The actual implementation will depend on you, but this style has worked well for me.
I am trying to use jQuery Validate to prevent my ajax form submit when three fields contain any characters other than digits. Apparently I'm doing something wrong, but I can't see what.
EDIT: There seem to be two errors. My validation rules use the field ID instead of the field name. However, after fixing that problem, the form still validates unexpectedly..
This is my jQuery code:
(function() {
$(document).ready(function() {
formSubmits();
/**
* Handles all the form submits that go on.
* This is primarily the ID search and the form submit.
*/
function formSubmits() {
/*** SAVE RECIPE ***/
// validate form
$("#category-editor").validate({
rules: {
"time-prep": {number: true}, /* not sure why validation doesn't work.. */
"time-total": {number: true}, /* according to this, it should: http://goo.gl/9z2odC */
"quantity-servings": {number: true}
},
submitHandler: function(form) {
// submit changes
$.getJSON("setRecipe.php", $(form).serialize() )
.done(function(data) {
// de-empahaize submit button
$('.footer input[type=submit]')
.removeClass('btn-primary')
.addClass('btn-default');
});
// prevent http submit
return false;
}
});
}
});
})(jQuery);
Here's what I see in the inspector when I put a breakpoint inside the submitHandler. It is getting to the submitHandler despite bad input (a value of 'dsdfd' instead of '123')
This is the relevant markup:
<form id="category-editor" class="form-inline" method="get">
....
<div class='form-group'>
<div>
<label for="time-prep">Prep time (min):</label>
<input value="" id="time-prep" name="activeTime" class="form-control min-calc jqValidateNum" data-calc-dest="time-prep-desc" type="number">
<input value="" id="time-prep-desc" name="activeTimeDesc" class="form-control subtle" type="text">
</div>
</div>
<div class='form-group'>
<div>
<label for="time-total">Total time (min):</label>
<input value="" id="time-total" name="totalTime" class="form-control min-calc jqValidateNum" data-calc-dest="time-total-desc" type="number">
<input value="" id="time-total-desc" name="totalTimeDesc" class="form-control subtle" type="text">
</div>
</div>
<div class='form-group'>
<div>
<label for="quantity-servings">Servings:</label>
<input value="" id="quantity-servings" name="servings" class="form-control jqValidateNum" type="number">
</div>
</div>
....
</form>
You've got your rules set up with the "id" values for the <input> elements instead of their "name" values. Should be:
rules: {
"activeTime": {number: true},
"totalTime": {number: true},
"servings": {number: true}
},
edit — now that you've fixed that, I think the problem is that the "value" properties of the input elements are empty, because you've declared them type=number. Firefox and Chrome let you type anything into the fields, but they won't have a non-empty value unless the fields really do contain numbers.
If you also mark the fields as required, then it works. fiddle