In one of my textbox i need to enter only multiple url or multiple text at a time,not both.
So while i use the regular expression given below the domain name "google.com" will satisfy the condition of text.But i need to return false for this type of entry.Can anyone please suggest an idea?
jQuery.validator.addMethod("newway", function(value, element) {
var testarray = ['.....'];
var url_count = 0;
var text_count = 0;
for(var k in testarray){
if(/^(http:\/\/|https:\/\/)?((([\w-]+\.)+[\w-]+)|localhost)(\/[\w- .\/?%&=]*)?/i.test(testarray[k]))
{
console.log("url");
url_count++;
}
else{
if(/^[a-zA-Z+,:;%()]+$/.test(testarray[k])){
console.log("text");
text_count++;
}
}
}
if((url_count==0 && text_count > 0) || (url_count >0 && text_count == 0)){
if((url_count==testarray.length) || (text_count==testarray.length)){
return true
}
else{
return false
}
}else{
return false
}
}, "Please enter url or text");
Related
How can I find out if a text input is a certain text?
I tried this
<script>
var b = document.getElementById('button')
var u = document.getElementById('username')
var p = document.getElementById('password')
var bannedUsers = ["user1012"];
b.onclick = function() {
if(u.value.length <= 20 && p.value.length >= 6 && u.value.length >= 3 && !u.value === bannedUsers) {
location.href = "";
};
if(u.value.length > 20) {
return alert('Username needs to be below 20 characters.')
} else if(u.value.length < 3) {
return alert('Username needs to be above 2 characters')
}
if(p.value.length < 6) {
return alert('Password needs to be over 6 characters.')
}
if(u.value === bannedUsers) {
return alert('That username is banned.')
}
}
</script>
But it ended up just taking me to the page instead of saying "This username is banned"
You need to use the includes method.
bannedUsers.includes(u.value)
what you're doing right now is checking if the string is the array bannedUsers, translating to this: 'user1012' === '[object Object]'
You can use the Array.prototype.includes method to test if a given value is in an array. includes will return a boolean true or false.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes
if (bannedUsers.includes(u.value) {
return alert('That username is banned.')
}
I'm currently using JavaScript code to validate a text field when the user types in letters a-z.
The script shows a tick if this is valid and a cross if its not. Now I am trying to add to the code to say check that the letters meet a minimum length of at least 4 characters, and if the min characters is met then show the tick and if the text is under the min character length show the cross.
How can I adjust my script to check the minimum length of the characters entered? Also can someone show me how I can allow '-' to be allowed in my validation?
script:
<script>
function validateCname(CnameField){
var reg = /^[A-Za-z]+$/;
if (reg.test(CnameField.value) == false)
{
document.getElementById("emailTick").style.display='none'; // Hide tick if validation Fails
document.getElementById("emailCross").style.display='block';
return false;
}
if (reg.test(CnameField.value) == true)
document.getElementById("emailCross").style.display='none';
document.getElementById("emailTick").style.display='block';
return true;
}
</script>
tried:
<script>
function validateCname(CnameField){
var reg = /^[A-Za-z]+$/;
var len = {min:4,max:60};
if (reg.test(CnameField.value) == false)
if(input.value.length>!=len.min) return flase;
{
document.getElementById("emailTick").style.display='none'; // Hide tick if validation Fails
document.getElementById("emailCross").style.display='block';
return false;
}
if (reg.test(CnameField.value) == true)
document.getElementById("emailCross").style.display='none';
document.getElementById("emailTick").style.display='block';
return true;
}
</script>
Almost there but you have a few syntax issues, so I've created an example test script for you:
function validateValue(value) {
var reg = /^[A-Za-z]+$/g;
var len = {min:4,max:60};
if (!reg.test(value)) {
console.log('didn\'t match regex');
return false;
}
if (value.length < len.min || value.length > len.max) {
console.log('incorrect length: ' + value);
return false;
}
console.log('correct length: ' + value);
return true;
}
validateValue('teststring');
Notice how I have set up the regex test, removing the == false? It's not needed because either false or array is returned. A true test will return true if anything other than null or false is returned.
Try this
<script>
function validateCname(CnameField){
var reg = /^[A-Za-z]+$/;
var len = {min:4,max:60};
if (reg.test(CnameField.value) == false) {
if(input.value.length<len.min)
{
document.getElementById("emailTick").style.display='none'; // Hide tick if validation Fails
document.getElementById("emailCross").style.display='block';
return false;
}
return false;
}
if (reg.test(CnameField.value) == true)
document.getElementById("emailCross").style.display='none';
document.getElementById("emailTick").style.display='block';
return true;
}
</script>
const validateCname = value => value.length < 4 ? `success message` : `error message`
function validateCname(value1)
{
var k = value1;
if(k.length<4){
//Your code if length is less than 4
}else{
//Your code if length is more than 4
}
}
In Australia we have area codes 02,03,07,08 however when i try to put 04 into the field it allows the form to be submitted when it should not allow it.
I am wondering if anyone knows how to fix this please.
function phtest(){
OTHERRegex = /^[07]{2}[0-9]{8}$/
NSWRegex = /^[02]{2}[0-9]{8}$/
VICRegex = /^[03]{2}[0-9]{8}$/
WARegex = /^[08]{2}[0-9]{8}$/
if (document.getElementById('phone2').value != '' || NSWRegex.test(document.getElementById('phone2').value)
|| VICRegex.test(document.getElementById('phone2').value)
|| WARegex.test(document.getElementById('phone2').value)
|| OTHERRegex.test(document.getElementById('phone2').value))
alert('Please input correct Landline Phone Field\n');
return false;
else
return true;
}
When you don't enclose the if / else in curlybraces, you close it with semicolons, so the alert closes the if, and the return false does nothing.
function phtest(){
var elem = document.getElementById('phone2');
if (/^[(02|03|07|08)]{2}[0-9]{8}$/.test(elem.value)) {
return true;
}else{
alert('Please input correct Landline Phone Field\n');
return false;
}
}
FIDDLE
You have missed curly braces in your if statement. So, you will get false anyway.
if (document.getElementById('phone2').value != '' || NSWRegex.test(document.getElementById('phone2').value)
|| VICRegex.test(document.getElementById('phone2').value)
|| WARegex.test(document.getElementById('phone2').value)
|| OTHERRegex.test(document.getElementById('phone2').value))
{
^^^
alert('Please input correct Landline Phone Field\n');
return false;
}
^^^
else
{
return true;
}
I have modified your code, you can try it:
function testPattern(phone){
var OTHERRegex = /^[07]{2}[0-9]{8}$/,
NSWRegex = /^[02]{2}[0-9]{8}$/,
VICRegex = /^[03]{2}[0-9]{8}$/,
WARegex = /^[08]{2}[0-9]{8}$/;
return (VICRegex.test(phone)
|| WARegex.test(phone)
|| NSWRegex.test(phone)
|| OTHERRegex.test(phone));
}
function phtest(){
var phone = document.getElementById('phone2').value;
var isValid = (phone
&& phone.length > 0
&& testPattern(phone));
if (!isValid) alert('Please input correct Landline Phone Field\n');
return isValid;
}
Try this. It is good for almost all formats - +61255555555, 0255555555, +61 2 5555 5555, +61-2-5555-5555
function validateLandline(numberStr) {
var landlineRegex = /^((00|\+)61|0)(2|3|7|8)\d{8}$/;
return landlineRegex .test(numberStr.replace(/ /g,'').replace(/-/g,''));
}
validateLandline('+61255555555') // true
validateLandline('+61-2-5555-5555') // true
validateLandline('+61 2 5555 5555') // true
validateLandline('0255555555') // true
validateLandline('02 55555555') // true
validateLandline('+61455555555') // false
validateLandline('0455555555') // false and so on
This is my first webpage in which I prompt the user for a phone number to add to a Do Not Call List database. Everything is working so far but I need to add the following, which I can do following the advice in this answer
stripping the input from all characters except digits
validating that the resulting string is 10 digits long
Then, when telling the user that the number was added to the list, I want to present it in the (999) 999-9999 format.
Where should I add all that code? Iside the #{ } block? In JavaScript? Razor?
Check phone number
function IsNumber(s) {
var i, currentCharacter;
for (i = 0; i < s.length; i++) {
// Check that current character is number.
currentCharacter = s.charAt(i);
if (((currentCharacter < "0") || (currentCharacter > "9"))) {
return false;
}
}
// All characters are numbers.
return true;
}
function TestInternationalPhone(strPhone) {
var bracket = 3,
openBracket,
phoneNumberOnly,
phoneNumberDelimiters = "()- ",
validWorldPhoneChars = phoneNumberDelimiters + "+",
minDigitsInIPhoneNumber = 10;
strPhone = SOS.StringHelper.Trim(strPhone);
if (strPhone.length === 0) {
return false;
}
if (strPhone.indexOf("+") > 1) {
return false;
}
if (strPhone.indexOf("-") != -1) {
bracket = bracket + 1;
}
if (strPhone.indexOf("(") != -1 && strPhone.indexOf("(") > bracket) {
return false;
}
openBracket = strPhone.indexOf("(");
if (strPhone.indexOf("(") != -1 && strPhone.charAt(openBracket + 2) != ")") {
return false;
}
if (strPhone.indexOf("(") == -1 && strPhone.indexOf(")") != -1) {
return false;
}
phoneNumberOnly = SOS.StringHelper.StripCharsInBag(strPhone, validWorldPhoneChars);
return (IsNumber(phoneNumberOnly) && phoneNumberOnly.length >= minDigitsInIPhoneNumber);
}
I am trying to do a Javascript form validation, and I want to set the formValue to 0 in several cases. That is, if ANY of the required fields are not filled out, the value should go to 0.
function formValidation() {
var formValue = 1;
if (document.getElementById('orgname').value == '') formValue = 0;
else if (document.getElementById('culture[]').value == '') formValue = 0;
else if (document.getElementById('category[]').value == '') formValue = 0;
else if (document.getElementById('service[]').value == '') formValue = 0;
if (formOkay == 1) {
return true;
} else if (formOkay == 0) {
alert('Please fill out all required fields');
return false;
}
}
Is there a more elegant way to do this?
EDIT: Script does not appear to be working, now.
You can do some looping:
var toCheck = ['orgname', 'culture[]', 'category[]', 'category[]']
for(var id in toCheck )
{
if(document.getElementById(id).value == ''){
formValue = 0;
break;
}
}
A more elegant way can be that you specify a 'required' class on each input that you want to check and than do the following using jQuery:
$(document).ready(function(){
var toCheck = $('.required');
var formValue = 1;
$.each(toCheck, function(index, element){
if(element.val() == '')
formValue = 0;
});
});
I've done this in other languages using boolean logic, taking advantage of the & operator. It always returns false if any of the values are false.
Something like:
function formValidation() {
var formValue = true;
formValue &= document.getElementById('orgname').value != '';
formValue &= document.getElementById('culture[]').value != '';
formValue &= document.getElementById('category[]').value != '';
formValue &= document.getElementById('service[]').value != '';
if(!formValue) {
alert('Please fill out all required fields');
}
return formValue;
}
This has the advantage of working for other scenarios where your logic is more complicated. Anything that evaluates in the end to true/false will fit right in with this solution.
Then I'd work on reducing logic duplication:
function formValidation() {
var formValue = true;
var elementIdsToCheck = ['orgname', 'culture[]', 'category[]', 'category[]'];
for(var elementId in elementIdsToCheck) {
formValue &= document.getElementById(elementId).value != '';
}
if(!formValue) {
alert('Please fill out all required fields');
}
return formValue;
}
Something like this should help (this assumes that value attribute is available on the referenced elements):
var ids = ["orgname", "culture[]", "category[]", "service[]"],
formValue = 1; // default to validation passing
for (var i = 0, len = ids.length; i < len; i++) {
if (document.getElementById(ids[i]).value === "") {
formValue = 0;
break; // At least one value is not specified so we don't need to continue loop
}
}
Building upon #Baszz's second answer using jQuery, you could also build a more generic solution using HTML5 data- attributes:
$(function() {
$('form').submit(function() {
var toValidate = $(this).find('input[data-validation]');
for(var i=0; i<toValidate.length; i++) {
var field = $(toValidate[i]);
if(field.val().search(new RegExp(field.data('validation'))) < 0) {
alert("Please fill out all required fields!");
return false;
}
}
});
});
You can then specify regular expressions in your markup:
<form>
<input type="text" data-validation=".+" />
</form>
For required fields you can use ".+" as a regular expression, meaning the user has to enter at least one character, but you can of course use the full potential of regular expressions to check for valid email addresses, phone numbers or zip codes etc...