jQuery validate URL without http:// [duplicate] - javascript

This question already has answers here:
How to make url validation without http ( or add it after validation passed )?
(3 answers)
Closed 4 years ago.
I'm trying to validate a url without http:// using jQuery validate but it's not working. I am following the mtosic's answer from here
<form id="form" method="post" action="#">
<input type="text" name="url" id="url" />
<button type="submit">Submit</button>
</form>
$.validator.addMethod('validUrl', function(value, element) {
var url = $.validator.methods.url.bind(this);
return url(value, element) || url('http://' + value, element);
}, 'Please enter a valid URL');
$("#form").validate({
rules: {
"url": {
url: "validUrl"
}
},
submitHandler: function (form) {
alert('valid form submitted');
return false;
}
});
When I type in an address like "www.google.com" I still get the invalid error.
Here's the fiddle
What is the issue? Thank you for the help

The problem is because you've defined the rule named validUrl, yet you're still setting the url rule on the element in the $.validate settings. Also note that you want to pass a boolean value to the property, not a string. Try this:
$(document).ready(function() {
$.validator.addMethod('validUrl', function(value, element) {
var url = $.validator.methods.url.bind(this);
return url(value, element) || url('http://' + value, element);
}, 'Please enter a valid URL');
$("#form").validate({
rules: {
"url": {
validUrl: true // <-- change this
}
},
submitHandler: function(form) {
alert('valid form submitted'); // for demo
return false; // for demo
}
});
});
body {
padding: 20px;
}
label {
display: block;
}
input.error {
border: 1px solid red;
}
label.error {
font-weight: normal;
color: red;
}
button {
display: block;
margin-top: 20px;
}
<script type="text/javascript" src="//code.jquery.com/jquery-2.0.2.js"></script>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<link rel="stylesheet" type="text/css" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/additional-methods.js"></script>
<form id="form" method="post" action="#">
<input type="text" name="url" id="url" />
<button type="submit">Submit</button>
</form>

Related

Validation issue in select2 multiple select

I'm trying to validated select2 and other input fields they are validating as shown in code snippet, but i do not want to show text on validation error instead i want to show red border around select2 and textbox, i have used that too in error placement and highlight section but it is not showing any red border around fields.
$("#singleselect").select2({ placeholder: "Please select",width: '100%'});
$.validator.messages.required = '';
$("form#msform").validate({
ignore:'input[type=hidden]',
rules:
{
"singleselect[]": { required: true },
name: { required: true }
},
errorPlacement: function (error, element) {
var elem = $(element);
if (elem.hasClass("select2-hidden-accessible")) {
element = $("#select2-" + elem.attr("id") + "-container").parent();
error.insertAfter(element);
}
else {
error.insertAfter(element);
}
},
highlight: function (element, errorClass, validClass) {
var elem = $(element);
if (elem.hasClass("select2-hidden-accessible")) {
$("#select2-" + elem.attr("id") + "-container").parent().addClass(errorClass);
}
else if(elem.is(':checkbox'))
{
elem.addClass("parent-error");
}
else {
elem.addClass(errorClass);
}
},
unhighlight: function (element, errorClass, validClass) {
var elem = $(element);
if (elem.hasClass("select2-hidden-accessible")) {
$("#select2-" + elem.attr("id") + "-container").parent().removeClass(errorClass);
}
else if(elem.is(':checkbox'))
{
elem.removeClass("parent-error");
}
else {
elem.removeClass(errorClass);
}
},
success: function (label, element) {
//jQuery(element).parent().removeClass('has-error');
},
submitHandler: function(form) {
form.submit();
}
});
span.error{
outline: 1px solid red;
border: 1px solid red;
}
.parent-error {
outline:1px solid red;
background:red;
}
#msform label.error {
display: none !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.2/select2.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.13.1/jquery.validate.min.js"></script>
<form action="#" id="msform" method="post" accept-charset="utf-8" novalidate="novalidate">
<select class="sl" id="singleselect" name="singleselect[]" multiple>
<option value="val1">Val-1</option>
<option value="val2">Val-2</option>
</select>
<input type="text" name="name" value="" id="name" maxlength="80" size="30" class="form-control error" autocomplete="off" placeholder="Name" aria-invalid="true">
<input type="submit" name="register" value="Register" class="btn btn-primary">
</form>
Your problem has to do with your targeting logic.
if (elem.hasClass("select2-hidden-accessible"))
You do not have anything in the DOM with that class. The hidden select element only has a class of sl.
Then you are trying to target an element with an ID of select2-" + elem.attr("id") + "-container", however, no such thing exists. I set up a jsFiddle, inspected the DOM, and the ID of the container is s2id_singleselect.
https://jsfiddle.net/8ganq0mt/1/
I also removed a lot of unnecessary code. There is no need to blank out the actual message or hide with CSS. If you don't want error messages, then don't use the errorPlacement callback to place the messages; just return false and messages are gone.
errorPlacement: function() {
return false;
},

How to use Jquery validation on the radio button with respected fields?

My issue is regarding jquery validation. I have a form and validation is working on input field but I am confused how to use the validation on the radio button because I have three radio buttons and the user can choose only one. All the radio button have their respected fields. I have to set the validation on it.
Example: I choose the first radio then the user should enter the book1 and book2 fields as well. If you choose the second radio then the user should enter the fruit1 and fruit2 fields value.
if user choose only radio button and without filling the fields details and clicked on submit then validation should display.
I tried some code. It's working for first radio button but what if any user chooses a second radio button?
This is the output I am getting.
Radio button Book is checked with Jquery validation if fields are empty
Notice here I choose fruit and clicked on submit button but validation is not displaying
The reason was I am not getting because I added only book radio button validation. Now how to use for fruit and subject?
book1: {required: true},
book2: {required: true}
$(document).ready(function() {
$("input[name='books_fruit_sub']").click(function() {
var test = $(this).val();
$(".show_fields").hide();
$("#show" + test).show();
});
$('#form').validate({ // initialize the plugin
rules: {
mobile: {
required: true,
number: true,
minlength: 10,
maxlength: 10
},
book1: {
required: true
},
book2: {
required: true
}
},
submitHandler: function(form) { // for demo
form.submit();
}
});
});
ul {
text-decoration: none;
margin: 0;
padding: 0;
}
ul li {
display: inline-block;
}
.error {
color: red;
}
<form action="" id="form">
<input type="text" name="mobile" placeholder="Mobile">
<ul>
<li>
<input type="radio" name="books_fruit_sub" id="books" value="books" checked>
<label for="books">Books</label>
</li>
<li>
<input type="radio" name="books_fruit_sub" id="fruit" value="fruit">
<label for="fruit">Fruit </label>
</li>
<li>
<input type="radio" name="books_fruit_sub" id="subject" value="subject">
<label for="subject">Subject </label>
</li>
</ul>
<div>
<div class="show_fields" id="showbooks">
<input type="text" name="book1" placeholder="Book 1">
<input type="text" name="book2" placeholder="Book 2">
</div>
<div class="show_fields" id="showfruit" style="display: none;">
<input type="text" name="fruit1" placeholder="Fruit 1">
<input type="text" name="fruit2" placeholder="Fruit 2">
</div>
<div class="show_fields" id="showsubject" style="display: none;">
<input type="text" name="subject1" placeholder="Subject 1">
<input type="text" name="subject2" placeholder="Subject 2">
</div>
</div>
<input type="submit" name="send" value="Submit">
</form>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/jquery.validate.min.js"></script>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.0/additional-methods.js"></script>
Just use a function that return true or false depending on if the related radio buttton is selected or not.
book1: {
required: function() {
return $('#books').is(':checked');
}
},
book2: {
required: function() {
return $('#books').is(':checked');
}
},
fruit1: {
required: function() {
return $('#fruit').is(':checked');
}
},
fruit2: {
required: function() {
return $('#fruit').is(':checked');
}
},
..
To be consequent use the plural form "fruits" and "subjects" as you did for "books" for your radio-buttons.
Here is your modified and working code in plunker.
You don't need jQuery for that. Using ES20xx, data-attributes and css it's fairly easy to create your own form validation. Let's, just for fun, work out an example based on your code.
We need a function to determine the chosen value of a radio button, that's checkRadio in the snippet;
We need a function to show or hide fields belonging to a radio button choice, that's switchFieldsBasedOnRadioChoice in the snippet. That function is activated by clickHandling. We use the chosen value from checkRadio to identify div#show[chosen value]] to be able to show the right div containing the input elements belonging to the chosen value;
We need an Object containing some methods to check fields denoted in html by data-check and activated by the value of [data-check], it's called fieldChecks;
We need a handler function for the (submit) button which will check all fields denoted by [data-check] for field value validity and warn if the field value is not valid, that's checkValues, activated by clickHandling;
We also create a focusin-handler that removes warnings from a previous input values check if the user clicks on or focuses one of the form fields;
We use data-attributes and css to style and display the warning values. Every text-input is wrapped in a div. We use the css class .invalid for (input fields container)-div that to style the warnings on the containing input fields (if applicable).
Notes
the handlers (click, focusin) in this snippet use event delegation.
client side validation is never sufficient. You should always check the fields values server side too before handling them at the server.
see also
// check value of a radio button
const checkRadio = name => {
const isChecked =
Array.from(document.querySelectorAll(`[name='${name}']`))
.filter(rb => rb.checked);
return isChecked.length ? isChecked[0].value : null;
};
// validity checks for field values ([data-check])
const fieldChecks = {
mobile: value => {
const valueClean = value.replace(/[^\d]/g, "");
return {
cando: valueClean.length === 10,
instruction: "Invalid: need 10 digits, you can use spaces and '-'"
};
},
booksOrFruits: value => ({
cando: value.trim().length >= 5,
instruction: "Invalid: all fields ≥ 5 characters"
}),
};
// add event listeners
document.addEventListener("click", clickHandling);
document.addEventListener("focusin", removeWarnings);
// click handling delegate
function clickHandling(evt) {
const origin = evt.target;
if (origin.type === "radio") {
return switchFieldsBasedOnRadioChoice(origin);
} else if (origin.id === "validate") {
return checkValues();
}
}
// focusin handling delegate: remove warnings on focus
function removeWarnings() {
console.clear();
Array.from(document.querySelectorAll(".notvalid"))
.forEach( el => el.classList.remove("notvalid") );
}
// check all field values and warn for invalid values in required fields
function checkValues() {
console.clear();
const checks = Array.from(document.querySelectorAll("[data-check]"));
let cando = true;
checks.forEach( input => {
// check for existence of input.dataset.check
if (!fieldChecks[input.dataset.check]) {
throw new Error(
`You forgot to add '${input.dataset.check}' to fieldChecks!`
);
}
const parent = input.parentNode;
// don't check input values from parent class "show_fields hidden"
if (parent.classList.contains("show_fields")
&& parent.classList.contains("hidden")) {
return false;
}
// perform the check denoted by [data-check] from the input field
const fieldChck = fieldChecks[input.dataset.check](input.value);
// if invalid value, use css/data-attributes to style a warning
if (!fieldChck.cando) {
parent.classList.add("notvalid");
if (fieldChck && fieldChck.instruction) {
parent.dataset.instruction = fieldChck.instruction;
}
cando = false;
} else {
parent.classList.add("valid")
}
} );
// all fields checked out ok
if (cando) { console.log("you're ok"); }
}
// show input fields belonging to a chosen radio input field
function switchFieldsBasedOnRadioChoice(origin) {
Array.from(document.querySelectorAll(".show_fields"))
.forEach(v => v.classList.add("hidden"))
const chosenValue = checkRadio(origin.name);
document.querySelector(`#show${chosenValue}`)
.classList.remove("hidden");
}
body {
margin: 2em;
font: normal 12px/15px verdana, arial, sans-serif;
}
input[type=text] {
margin: 0.3em 0.3em 0 0;
padding: 2px 4px;
}
button {
margin-top: 0.3em;
}
/* fields originating from radio choice */
.show_fields {
display: table-row;
visibility: "visible";
opacity: 1;
transition: opacity ease-in 0.5s 0s;
}
.hidden {
opacity: 0;
transition: opacity ease-out 0.1s 0s;
visibility: collapse;
}
/* styling related to validation */
.notvalid input {
border: 1px solid red;
}
.notvalid[data-instruction]:after {
content: attr(data-instruction);
margin-left: 0.2em;
}
.notvalid ::placeholder {
color: red;
}
.valid:after {
font-weight: bold;
content: "\2714";
color: green;
}
.valid input {
color: green;
}
<ul>
<li>
<input type="radio" name="books_fruit_sub" id="books" value="books" checked>
<label for="books">Books</label>
</li>
<li>
<input type="radio" name="books_fruit_sub" id="fruit" value="fruit">
<label for="fruit">Fruit </label>
</li>
</ul>
<div data-required>
<input type="text" name="mobile" placeholder="mobile" data-check="mobile">
</div>
<div>
<input type="text" name="notrequired" placeholder="not required">
</div>
<div class="show_fields" id="showbooks">
<input type="text" name="book1" placeholder="Book 1" data-check="booksOrFruits">
<input type="text" name="book2" placeholder="Book 2" data-check="booksOrFruits">
</div>
<div class="show_fields hidden" id="showfruit">
<input type="text" name="fruit1" placeholder="Fruit 1" data-check="booksOrFruits">
<input type="text" name="fruit2" placeholder="Fruit 2" data-check="booksOrFruits">
</div>
<button id="validate">Check</button>
Remove the rule for book1 and book2 from validator initialization and in your click handler just add this
$(".show_fields").find("input").removeAttr("required");
$("#show" + test).find("input").attr("required" , "required");
Also in html add required attribute to both inputs book1 and book2

Validating user input with try and catch with jQuery

I want to validate whatever the values of the inputs are using try and catch. Every time the user gives a wrong value I want a a message to appear next to the input box that filled wrong.
The problem is that the every time it executes, the wrong message appears in both input boxes and I don't want to put many conditions. I just want to make it as simple as possible. I don't have a clue what conditions I should use.
$(document).ready(function() {
$("#btn").click(function() {
var inputArr = [$("#name").val(), $("#lName").val()];
var regexArr = [new RegExp("\^[a-zA-z]+$"), new RegExp("\^[a-zA-z]+$")];
for (var i = 0; i < inputArr.length; i++) {
fn(regexArr[i], inputArr[i]);
} //for loop
function fn(exp, str) {
var res = exp.test(str);
try {
if (res == false) {
throw Error("wrong");
}
} catch (e) {
alert(e);
$("#empty1").fadeIn(3000);
$("#empty1").html(e);
$("#empty1").fadeOut(3000);
$("#empty2").fadeIn(3000);
$("#empty2").html(e);
$("#empty2").fadeOut(3000);
} //try and catch
} //function
}); //button
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
Name<input id="name"><span id="empty1"></span></br>
</br>
Last Name<input id="lName"><span id="empty2"></span></br>
</br>
<button id='btn'>Click</button>
</body>
</html>
For form validations, its better using Jquery validation plugin. It is very simple and needs Jquery library included in it. Try this https://jqueryvalidation.org/. Please refer this js fiddle also https://jsfiddle.net/jfc62uof/6/
<form action="javascript:void(0)" id="myform" role="form" enctype="multipart/form-data" method="POST">
<div class="form-group">
<label><b>Password</b></label>
<input type="password" class="form-control" placeholder="Password" name="psw" id="psw">
</div>
<div class="form-group">
<label><b>Repeat Password</b></label>
<input type="password" class="form-control" placeholder="Repeat Password" name="rpsw">
<span id='message'></span>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" name="submit" value="save">
</div>
</form>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/jquery.validate.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.17.0/additional-methods.min.js"></script>
<script>
$("#myform").validate({
rules: {
psw: {
required: true
},
rpsw: {
equalTo: "#psw"
}
}
});
</script>
Since you want it according to what has been asked of you to do,
$(document).ready(function() {
$("#btn").click(function() {
var inputArr = [$("#name").val(), $("#lName").val()];
var regexArr = [new RegExp("\^[a-zA-z]+$"), new RegExp("\^[a-zA-z]+$")];
for (var i = 0; i < inputArr.length; i++) {
fn(regexArr[i], inputArr[i],i+1);
} //for loop
function fn(exp, str, no) {
var res = exp.test(str);
try {
if (res == false) {
throw Error("wrong");
}
} catch (e) {
//alert(e);
if($('#err').length==0)
$("#empty"+no).val('').addClass('error').after('<p style="display:inline;" id="err">'+e+'</p>');
} //try and catch
} //function
}); //button
});
where error class can have css like
.error{
border: 2px solid red;
background-color: #f7b9d9;
}

Text field group validation using jquery validator

Currently working with jquery group field validation. I am using the great jquery validation plugin I have searched through SO actually I got some idea for group validation with my current code I can able to validate the three field and when i typed in any of the field the errClass getting disappear but the validation count was not detecting.
I was not able to figure out what was the problem
Here is the jquery code
$(document).ready(function () {
$(".error_msge").hide();
$(".basicForm").validate({
ignore: false,
onkeyup: false,
showErrors: function (errorMap, errorList) {
var errors = this.numberOfInvalids();
if (errors) {
var message = errors == 1 ? 'You missed 1 field. It has been highlighted' : 'You have missed ' + errors + ' fields. Please fill the highlited field before submit.';
$("#error_message").html(message);
$(".error_msge").show();
} else {
$(".error_msge").hide();
}
this.defaultShowErrors();
},
errorPlacement: function () {
return false;
},
highlight: function (element) {
if ($(element).is(':radio')) {
} else {
$(element).addClass('errRed');
}
$(element).prevAll('label').find('span.required-star').addClass('text-error-red').removeClass('text-error-black');
},
unhighlight: function (element) {
if ($(element).is(':radio')) {
} else {
$(element).removeClass('errRed');
}
$(element).prevAll('label').find('span.required-star').addClass('text-error-black').removeClass('text-error-red');
},
rules: {
txt_Po: {
require_from_group: [1, ".txt_Add"]
},
txt_Bdg: {
require_from_group: [1, ".txt_Add"]
},
txt_St: {
require_from_group: [1, ".txt_Add"]
}
}
});
});
Here is my HTML code
<span id="error_message" class="error_msge">
</span>
<form autocomplete="off" class="basicForm" id="basicForm" method="POST">
<!--first field-->
<label>P.O.Box</label>
<br/>
<input type="text" class="ipt_Field txt_Add" id="txt_Po" name="txt_Po" />
<!--second field-->
<label>Building</label>
<br/>
<input type="text" class="ipt_Field txt_Add" id="txt_Bdg" name="txt_Bdg" />
<!--third field-->
<label>Street</label>
<br/>
<input type="text" class="ipt_Field txt_Add" id="txt_St" name="txt_St" />
<button class="btn-next" id="btn-Next" >Next</button>
</form>
Here is the CSS code
.errRed {
color: black !important;
border: 1px solid #EA373D !important;
padding: 6px !important;
}
.error_msge {
border:1px solid red;
width: 450px;
margin: 0px auto;
text-align: center;
background-color: #FFBABA!important;
padding: 5px;
}
Thanks in advance

HTML code for validation

HTML code for validaton of name, mobile number etc by giving error message beside the text box in red colour
if(p.length!=10) region.innerHTML="phone num must be 10 digits";
if(isNaN(p)) region.innerHTML="digits only";
I have used this type of format but not working.
if you want to use html validation try this once:
<style type="text/css">
.validationError {
border: solid 2px red;
}
.validationValid {
border: solid 2px green;
}
</style>
<form id="customerForm">
<label>
First Name:
<input id="firstName" required />
</label>
<label>
Social Security Number:
<input id="ssn" required pattern="^[0-9]{3}-[0-9]{2}-[0-9]{4}$" title="Expected pattern is ###-##-####" />
</label>
<input type="submit" />
</form>
script:
<script type="text/javascript" src="js/jquery-1.4.4.min.js"></script>
<script type="text/javascript" src="js/jquery.h5validate.js"></script>
<script type="text/javascript">
// Enable h5Validate plugin
$("#customerForm").h5Validate({
errorClass: "validationError",
validClass: "validationValid"
});
// Prevent form submission when errors
$("#customerForm").submit(function (evt) {
if ($("#customerForm").h5Validate("allValid") === false) {
evt.preventDefault();
}
});
</script>
Try following function
var phoneNumber = "(07) 1234-5678";
phoneNumber = phoneNumber.replace(/\D/g,'');
if (phoneNumber.length == 10) {
region.innerHTML = phoneNumber + ' contains 10 digits';
}
else {
region.innerHTML= phoneNumber +' does not contain 10 digits';
}

Categories