jQuery validation engine, set minsize but allow empty - javascript

I have using jQuery validation engine,
I try to let empty text field, but validate while the field not empty
my code is like this
<input name="t_city" type="text" id="t_city" placeholder="CITY" class="validate[minSize[6]]">
and my javascript is like this
$("form").validationEngine({
onValidationComplete:function(form, status){
var city = $("input#t_city").val();
if(status == true){ alert(city); }
}
}
}
How to validate to allow if the input field is empty.?

change class="validate[minSize[6]]" to class="validate[optional,minSize[6]]"
HTML:
<input name="t_city" type="text" id="t_city" placeholder="CITY" class="validate[optional,minSize[6]]">

Related

Set focus to another field in web form with javascript

I have a web form with two fields:
Email
User name
I want to track user input in the Email field and when it ends with ".com" set focus to another field "User email"
What the best way to do so with JavaScript or jQuery.
This should do the trick. When the last 4 letters of the email input are '.com', the focus is given to the username field.
While this works, please consider the UX issues this may cause. In the comments for your question, Quentin provides a good explanation of why this probably isn't worth implementing.
$('#email').on('input', function() {
email = this.value
if (email.substr(email.length - 4) === '.com')
$('#username').focus()
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="email" type="text" placeholder="email">
<input id="username" type="text" placeholder="user name">
as #Quentin mentioned this not a best practice due to these types of emails such as (.com.au)
but if you really know what you are doing then this code does what you want
// select email input
const mail = document.getElementById('mail');
// add input event
mail.addEventListener('input', e => {
// get value
let value = e.target.value.trim();
const regex = /.com$/ig; // matches any string ends with .com
const result = regex.test(value);
// if matches .com at the end then add focus to name input
if (result) {
e.target.nextElementSibling.focus();
}
});
<form>
<input type="text" placeholder="insert your email" id="mail">
<input type="text" placeholder="insert your name" id="name">
</form>

pattern attribute only passes after page reset

I have added a pattern attribute to my custom input field in the Shopify add to cart form.
The problem is that the pattern validator won't pass unless i refresh the page after it has caught something in the validation.
I have tried to reset the form with .reset and it works, but the custom validation messages won't work in that case.
<input required class="required" id="add-your-name-here" type="text" pattern="^[A-Za-z_]{1,15}" placeholder="{{ section.settings.text-custom-name-placeholder }}" name="properties[Ditt namn]">
var input = document.getElementById('add-your-name-here');
input.oninvalid = function(event) {
if ($(".wgcurrent").hasClass("en")) {
event.target.setCustomValidity("Letters only please");
} else if ($(".wgcurrent").hasClass("sv")) {
event.target.setCustomValidity("Vänligen ange endast bokstäver");
}
}
It works like this, except that the custom validation message won't display.
var input = document.getElementById('add-your-name-here');
input.oninvalid = function(event) {
if ($(".wgcurrent").hasClass("en")) {
document.getElementById("addtocart").reset();
event.target.setCustomValidity("Letters only please");
} else if ($(".wgcurrent").hasClass("sv")) {
document.getElementById("addtocart").reset();
event.target.setCustomValidity("Vänligen ange endast bokstäver");
}
}
I want the validation to work without having to refresh the page as it's not a very nice user experience.
You need to clear the Custom Validation message on input event. To do so use,
setCustomValidity('');
Check working code snippet below.
var input = document.getElementById('add-your-name-here');
input.oninput = function(event){
event.target.setCustomValidity('');
}
input.oninvalid = function(event) {
event.target.setCustomValidity("Letters only please");
}
<form action="#">
<input required class="required" id="add-your-name-here" type="text" pattern="^[A-Za-z_]{1,15}" placeholder="Add text here" name="properties[Ditt namn]">
<button type="submit">Submit</button>
</form>
More details on Constraints Validation at MDN

URL validation in text input

How do I validate the url in a text input if the user accidentally write on the text input before clicking submit?
Try below code, this will work for you
function urlLocate() {
var url = document.getElementById("url").value;
var regexp = /^(?:(?:https?|ftp):\/\/)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/\S*)?$/;
if (url != "") {
if (!regexp.test(url)) {
alert("Please enter valid url.");
} else {
window.location.assign(url);
}
}
else {
alert("Please upload an image.");
}
}
try this function for Url validation.
function isUrlValid(userInput) {
var res = userInput.match(/(http(s)?:\/\/.)?(www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,6}\b([-a-zA-Z0-9#:%_\+.~#?&//=]*)/g);
if(res == null)
return false;
else
return true;
try this function for validating url
function ValidURL(str) {
var pattern = new RegExp('^(https?:\/\/)?'+ // protocol
'((([a-z\d]([a-z\d-]*[a-z\d])*)\.)+[a-z]{2,}|'+ // domain name
'((\d{1,3}\.){3}\d{1,3}))'+ // OR ip (v4) address
'(\:\d+)?(\/[-a-z\d%_.~+]*)*'+ // port and path
'(\?[;&a-z\d%_.~+=-]*)?'+ // query string
'(\#[-a-z\d_]*)?$','i'); // fragment locater
if(!pattern.test(str)) {
alert("Please enter a valid URL.");
return false;
} else {
return true;
}
}
Use form and <input type="url"> to validate it. The form can only be submitted with the valid value(s).
$('form').on('submit', function(e){
e.preventDefault();
console.log('valid URL');
});
<form>
Input a URL: <input type="url" required><br>
<input type="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I agree with #NoobTW and #Azer to use <input type="url"
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/url
Examples without any JS:
Demand a URL prefix but you can make one up yourself. Both http:// and bonk:// will be accepted as valid url prefixes.
<form>
<input type="url" required />
<input type="submit" value="Submit Now!">
</form>
URL validation by demanding that all url's start with either http:// or https://
<form>
<input type="url" pattern="https?://.+" required />
<input type="submit" value="Submit Now!">
</form>
Require https:
<form>
<input type="url" pattern="https://.+" required />
<input type="submit" value="Submit Now!">
</form>
https://html5-tutorial.net/form-validation/validating-urls/
With simple error message:
<form>
<input type="url" pattern="https://.+" required title="Requires https://" />
<input type="submit" value="Submit Now!">
</form>
If you wish to replace Default HTML5 Validation Message you can do it like this:
https://webdesign.tutsplus.com/tutorials/html5-form-validation-with-the-pattern-attribute--cms-25145#Replacing%20the%20Default%20HTML5%20Validation%20Message
type="url"
You can give the input type="url" to give it a simple validation as mentioned above.
<input type="url" required>
Please note that you should also give it the required attribute if a valid URL is required to submit the form.
pattern attribute
You can also give the input the pattern attribute if you want to add your own custom validation. The pattern attribute takes a regex pattern as it's value and will match it to the value of the input at validation. If you use a pattern attribute to do your own custom validation, you don't need to use the "url" input type. A simple text input will work as well.
<input type="text" pattern=".*\.[a-z]{2,}$" required>
The above is an overly simplified regex pattern that will only recognize very plain urls (like example.com) and should not be used for any serious validation. But you can change the pattern to any one of the patterns used in functions suggested in other answers, or some other pattern that fit your needs.
Both combined
<input type="url" pattern="https?:\/\/*" required>
The above is a simple example of a url input where a pattern attribute has been applied to make the validation a little bit stricter. This way the value of the input has to pass both the standard validation of a url input field, but it also has to pass the regex pattern to be validated. In the above example, the url has to begin with either http:// or https:// to pass validation.

Form submits regardless of validation

I have a form, and I've written a validation script for it, however, it's not working 100%. It outputs errors fine, but the submit button will submit the form, even if it has outputted the alert boxes. Anyone have any idea why?
Apparently not all the code pasted. I would just use the Required parameter, but I need JS validation as it is an assignment. Also, UL is defined before this part of code, as there is a list before this.
HTML:
<div class = "form">
<form name = "contactForm" onsubmit="validateForm()" action = "form.php">
<li><label>First name: </label><input type = "text" name = "fname" autofocus></li><br>
<li><label>Last Name: </label><input type = "text" name = "lname"></li><br>
<li><label>Email: </label><input type = "text" name = "email"> <button onclick = "validateEmail();return false">Check if email is valid</button> </li><br>
<li><label>Message: </label> <br>
<textarea rows = "10" cols = "50" name = "message"></textarea></li>
<li> <input type = "submit"> </li>
</form>
JavaScript:
function validateForm()
{
var x=document.forms["contactForm"]["fname"].value; //Gets the form and field name from the HTML
if (x==null || x=="") //If the field "fname" contains null, or nothing, then output an alert telling the user to input something into the field. Same goes for the rest of the code.
{
alert("First name must be filled out");
return false;
}
var x=document.forms["contactForm"]["lname"].value;
if (x==null || x=="")
{
alert("Last name must be filled out");
return false;
}
var x=document.forms["contactForm"]["email"].value;
var reg = /^([A-Za-z0-9_\-\.])+\#([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
if(reg.test(x) == false)
{
alert("Please enter a valid Email");
return false;
}
if (x==null || x=="")
{
alert("Email must be filled out");
return false;
}
var x=document.forms["contactForm"]["message"].value;
if (x==null || x=="")
{
alert("Message must be filled out");
return false;
}
}
You have to trigger event on time of submit. Like this way:
<form onsubmit="validateForm()">
How are you attaching the event listener? I’d wager it’s with:
<form … onsubmit="validateForm()">
You’d need return validateForm(). But wait! Don’t add that.
Your script does not check for valid e-mail addresses correctly. It only checks one error at once. It will annoy users. Use HTML5 validation and back it up with PHP.
By applying type="email", you don’t need a button at all, and mobile users will see an e-mail specific keyboard if available. The browser will validate it, given support.
<input type="email" name="email">
Required fields should use the required attribute.
<input type="text" name="fname" autofocus required>
&vellip;
<input type="text" name="lname" required>
Your labels aren’t correct either; they should surround the element they’re related to, or provide a for attribute matching the element’s id.
You should also validate your HTML. And not put <br>s between <li>s.
Finally, as general [client-side] JavaScript tips:
You don’t have to check the value of a text field for null.
Write !x instead of x == false.
You can also use JQuery to do something like this:
$( "#formId" ).submit(function( event ) {
if($("#nameInput").val() == "")
event.preventDefault();
});
So basically, if nameInput's equals to empty the submit action will be canceled
Take a look at here if you want: https://api.jquery.com/submit/
Good luck

How to create html5 custom validation?

I am using html 5 form validation for validate my form before submit, if is valid, submit, but I need validate my User Register form, so it need validate if Password Confirm value is equal camp Password, below is my form example:
<form>
<label>Login:</label>
<input type="text" name="login" id="login"/><br/>
<label>Password:</label>
<input type="password" name="pass" id="pass"/><br/>
<label>Password Confirm:</label>
<input type="password" name="pass_conf" id="pass_conf"/><br/>
<input type="submit"/>
</form>
or in jsfiddle
How to can I create my custom validation for work like default validations?
Well you can use JQuery and attach an attribute to be selected for the passwords to validate each other via input event. Use setCustomValidity() to set the message of the input affected to override the default message when the form is submitted.
See the updated fiddle.
As you can see in the fiddle, all you have to do is add an attribute data-equal-id wherein the attribute value must be the ID of password input element to be tested.
HTML
<h1>How to create html5 validation for password confirm?</h1>
<hr>
<form>
<label>Login:</label>
<input type="text" name="login" id="login"/><br/>
<label>Password:</label>
<input type="password" name="pass" id="pass"/><br/>
<label>Password Confirm:</label>
<input type="password" name="pass_conf" id="pass_conf" data-equal-id="pass" /><br/>
<input type="submit"/>
</form>
Javascript
$('[data-equal-id]').bind('input', function() {
var to_confirm = $(this);
var to_equal = $('#' + to_confirm.data('equalId'));
if(to_confirm.val() != to_equal.val())
this.setCustomValidity('Password must be equal');
else
this.setCustomValidity('');
});
you could try putting this code in your header:
<script>
document.getElementById('myform').onsubmit = function() {
if(!validateForm()){ // call your validation function
alert('fail!'); // remove this
return false; // prevent the form to submit
}
}
// your validation function
// compares that the passwords are equal
function validateForm(){
var pass = document.getElementById('pass').value;
var pass_conf = document.getElementById('pass_conf').value;
if(pass == pass_conf){
return true;
}else{
return false;
}
}
</script>
also put the id 'myform' to your form (or the name you want, but change it in the first line)
How about something fun like this using jQuery?
$('input[type="password"]').keyup(function() {
var pass=$('#pass').val();
var conf=$('#pass_conf').val();
if (pass == conf)
$('input[type="submit"]').removeAttr('disabled');
else
$('input[type="submit"]').attr('disabled', 'disabled');
});
The breakdown...
I am keying off of the keyup, so every time a key is pressed in the
password fields the function will fire.
I'm grabbing the value of both password fields, and comparing them.
If the values are the same, I'm enabling the submit button.
If the values are different, I'm disabling the submit button.
Pretty simple, but it works. Here is a demo: http://codepen.io/anon/pen/GxAyC/
(note - I added a couple of other visual enhancements to the demo to show what can be done)
You're using HTML5 for client-side form validation and wish to validate your form prior to form submission. Your form consists of three inputs and your only validation criteria is that both password fields match.
The most simple way to do this is to write a custom submit handler script:
const handleFormSubmit = (event) => {
event.preventDefault();
form = event.target;
if (form.pass === form.pass_conf) {
form.submit();
}
}
Above preventDefault() stops the default form submission behavior so you can execute your check. Then check if the value of the two password fields are equal. And if they are, continue form submission.
To use, attach the custom handler to your form by listening to the submit event:
const form = document.querySelector('form');
form.addEventListener('submit', handleFormSubmit);
Applied in context to example form provided:
<form>
<label>Login:</label>
<input type="text" name="login" id="login"/><br/>
<label>Password:</label>
<input type="password" name="pass" id="pass"/><br/>
<label>Password Confirm:</label>
<input type="password" name="pass_conf" id="pass_conf"/><br/>
<input type="submit"/>
</form>
<script>
const form = document.querySelector('form');
form.addEventListener('submit', handleFormSubmit);
const handleFormSubmit = (event) => {
event.preventDefault();
form = event.target;
if (form.pass.value === form.pass_conf.value) {
form.submit();
}
}
</script>

Categories

Resources