How to check for special characters when validating a form - javascript

I'm trying to add form validation into my form. I've managed to do it for character length, numbers, letters and all of them work fine, but it doesn't seem to work for special characters, such as # & * etc.
I've tried following an example from a previous question which created a variable for all the different special characters, and then I did here what I did with my other checks, matched the field input to the variable with the special characters to see if there are any, but it is not detecting them.
This is my JavaScript for this:
function ValidateActInsert() {
var specialChars = /[!##$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/;
if (document.actorInsert.actInsert.value.match(specialChars)) {
alert ("Only characters A-Z, a-z and 0-9 are allowed!")
document.actorInsert.actInsert.focus();
return false;
}
return (true);
}
And this is the HTML form that I am trying to do this on:
<form name = "actorInsert" align = "center" action="actorInserting.php" onSubmit="return ValidateActInsert()">
Actor name:<br>
<input type = "text" name = "actInsert"
<br><br>
<input type = "submit" value = "Insert">
</form>
The code itself makes sense to me and i'd imagine that it would work and I honestly have no idea as to why it isn't

You were catching every symbol.
Let's just simple only allow
a-z lowercase,
A-Z uppercase and or
0-9 as #SterlingArcher said.
/[^a-zA-Z ]/g Will allow only a-z and A-Z
/[^a-zA-Z0-9 ]/g Will allow only a-z, A-Z, and 0-9
Letters and Numbers:
function ValidateActInsert() {
var specialChars = /[^a-zA-Z0-9 ]/g;
if (document.actorInsert.actInsert.value.match(specialChars)) {
alert ("Only characters A-Z, a-z and 0-9 are allowed!")
document.actorInsert.actInsert.focus();
return false;
}
return (true);
}
<form name = "actorInsert" align = "center" action="actorInserting.php" onSubmit="return ValidateActInsert()">
Actor name:<br>
<input type = "text" name = "actInsert"
<br><br>
<input type = "submit" value = "Insert">
</form>
Numbers only
function ValidateActInsert() {
var specialChars = /[^a-zA-Z ]/g;
if (document.actorInsert.actInsert.value.match(specialChars)) {
alert ("Only characters A-Z, a-z are allowed!")
document.actorInsert.actInsert.focus();
return false;
}
return (true);
}
<form name = "actorInsert" align = "center" action="actorInserting.php" onSubmit="return ValidateActInsert()">
Actor name:<br>
<input type = "text" name = "actInsert"
<br><br>
<input type = "submit" value = "Insert">
</form>
I suggest using https://regexr.com/ to test expressions and to learn from some examples.

Use regex.test(val)
^[0-9a-zA-Z ]*$
^ start
[0-9a-zA-Z] only allow the characters inside [ ]
$ end * as many characters as it contains
function ValidateActInsert() {
var regex = /^[0-9a-zA-Z ]*$/;
var val = document.getElementsByTagName('input')[0].value;
if(!regex.test(val)){
alert("false");
}else{
alert("true");
}
return false;
}
<form name = "actorInsert" align = "center" action="actorInserting.php" onSubmit="return ValidateActInsert()">
Actor name:<br>
<input type = "text" name = "actInsert">
<br>
<input type = "submit" value = "Insert">
</form>

Related

Make button is disabled if space is typed in textarea

I'm making a system with JS with a form so that unless the user types something on a textbox, the submit button is enabled, else it will be disabled, but here's the problem: When the user types a space, the button became enabled. How can I make so the button isn't enabled unless the user types a letter? Here's the code I'm using:
function enable() {
if (document.getElementById("textsend").value === "") {
document.getElementById('main-submit-post').disabled = true;
document.getElementById('main-submit-post').style.filter = "brightness(50%)";
document.getElementById('main-submit-post').style.cursor = "auto";
} else {
document.getElementById('main-submit-post').disabled = false;
document.getElementById('main-submit-post').style.filter = "brightness(100%)";
document.getElementById('main-submit-post').style.cursor = "pointer";
}
}
<textarea name="content" id="textsend" onkeyup="enable()" placeholder="You can type here..."></textarea>
<hr>
<button type="submit" id="main-submit-post" disabled>Share</button>
As you can see, if you type just space, the button gets enabled. How can I make so it only gets enabled if the user types at the beginning a letter?
The ^ character anchors the regular expression to the start of the string.
The \s Matches a single character other than white space. Equivalent to [^ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]. For example, /\S\w*/ matches "foo" in "foo bar".
The \d Matches any digit (Arabic numeral). Equivalent to [0-9]. For example, /\d/ or /[0-9]/ matches "2" in "B2 is the suite number".
function enable() {
const mainSubmitPost =document.getElementById('main-submit-post');
const textSend = document.getElementById("textsend");
if (textSend.value === "" || textSend.value.match(/^\d/) || textSend.value.match(/^\s/) ) {
mainSubmitPost.disabled = true;
mainSubmitPost.style.filter = "brightness(50%)";
mainSubmitPost.style.cursor = "auto";
} else {
mainSubmitPost.disabled = false;
mainSubmitPost.style.filter = "brightness(100%)";
mainSubmitPost.style.cursor = "pointer";
}
}
<textarea name="content" id="textsend" onkeyup="enable()" placeholder="You can type here..."></textarea>
<hr>
<button type="submit" id="main-submit-post" disabled>Share</button>

How to validate my form in JS?

I'm trying to validate the full name part of my form, the requirements are:
Only alphabet, spaces between words and "-" are valid.
Minimum of 3 characters and max of 35.
My HTML code is as follows:
function test(myForm)
{
var regex = /^[a-zA-Z]+$/;
if(regex.test(myForm.full_name.value) == false) {
alert("Name must be in alphabets only");
myForm.full_name.focus();
return false;
}
}
<tr>
<td>
<b>Full Name: </b>
</td>
<td>
<input type="text" name="full_name" placeholder="Full Name" required/>
</td>
</tr>
Try this regex, which doesn’t allow space or - characters at the start or end of the string:
var regex = /^[a-zA-Z][a-zA-Z- ]{1,33}[a-zA-Z]$/
This regex should do the work for you /(^[a-zA-Z -]{3,35}$)/
Explanation:
[a-zA-z -] -- Any character space or -
{3,35} -- repeat between 3 to 35 times
Example:
function test(name) {
var regex = /(^[a-zA-Z -]{3,35}$)/
return regex.test(name)
}
console.log(test('valid-name'))
console.log(test('valid Name'))
console.log(test('valid'))
console.log(test('in'))
console.log(test('invalid~name'))
console.log(test('invalidname invalidname invalidname invalidname'))

<input type=“text” maxlength=“4”> should not count comma and dot in maxlength

I have input field which contains number and special characters e.g. comma and dot
while calulating the maxLength of the field i want to skip special characters .
I dont want to restrict the special character.
Expected Output should be :- 1,234 (Total Length :- 4)
<form action="/action_page.php">
Username: <input type="text" maxlength="3" id="myId"/>
<input type="submit" value="Submit">
</form>
jsfiddle link here
Try adding this javascript:
window.onload = function() {
var textInput = document.getElementById("myId");
textInput.oninput = function() {
var temp;
temp = this.value.replace(/[^\w\s]/gi,'');
if (temp.length > 3) {
alert("Invalid"); // Or other stuff you want to do
}
};
};
Note that this code checks input on real time
This should be done with javascript:
var input = document.getElementById('myId');
input.addEventListener('keyup', function () {
// Checking length of string ignoring all non-digit and non-letter characters
if (this.value.replace(/[^\d|[^a-zA-Z]]*/g, '').length == 3) {
console.log('stop and do whatever you need')
}
})
You can try to use HTML5 pattern attribute. Just instead of maxlength type pattern and give it some regex. Could do something like this:
<form action="/action_page.php">
Username: <input type="text" pattern="(?(?=^.\d{1,3},\d{1,3}$)^.{5}$|^.{4}$)" id="myId"/>
<input type="submit" value="Submit">
</form>

Check if the entire String value in Textbox is zero(0) or of special characters

I have a Textbox in which i'm getting the input of type text having the length 20, I have a scenario in which i have to evaluate whether the entire string input from the client is not zero or any special characters
e.g: 00000000000,00000,00,00000,00000/-/--,/-/-----////,aBadf-018---///sdf484,AA///---000
all these above inputs are invalid, the string could be of any length in between 2 to 20,
i have restricted the user to input other special characters other than hyphen and dash,
regex used over here to invalidate the value other than hyphen and dash are as follows :
" /[^a-zA-Z0-9/-]/g "
<input type="text" name="consumer_number" maxlength="25" ng-disabled="!form_data[selectedTab].electrici‌​ty.check" alpha-numeric-with-slash-and-hyphen data-ng-model="form_data[selectedTab].electric‌​ity.unique_no" class="input-field" data-ng-blur="validateElecConsumer(selectedTab‌​)" ng-class="{true:'invalid-field',false:''}[form‌​_data[selectedTab].e‌​lectricity.check && form_data[selectedTab].invalid.electricity]" required />
Now my concern is how could i display a message right upfront that whatever the input the user have provided is invalid.
This may help:
var app = angular.module("app", []);
app.controller("MyController", function($scope){
$scope.inputtext = "";
$scope.onSubmit = function() {
var val = $scope.inputtext;
if (val.length < 2
|| val.length > 20
|| !val.match(/[^a-zA-Z0-9/-]/g)) {
alert("Unacceptable");
} else {
alert("you pass");
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="MyController">
<input maxlength="20"
id="inputtext"
ng-model="inputtext" type="text"/>
<button id="submitbutton" ng-click="onSubmit()" type="text">submit</button>
</div>

How do I allow the user to only input a string?

function EnterCandidates() {
var candidateNameInputs = document.querySelectorAll('input[id^=C]'),
names = document.querySelectorAll('label[for^=V][id^=L_V]');
Array.prototype.forEach.call(names, function(label, index) {
if (candidateNameInputs[index].value !== candidateNameInputs[index].defaultValue) {
label.textContent = candidateNameInputs[index].value;
}
});
}
I have this code which gets the users input and changes the label with it but i want to add some code which only allows the user to enter letters of the alphabet. How would I go about this using this code?
If you are using modern browsers then user html5 validation -
<input type="text" name="name" class="field" pattern="[a-zA-Z ]+" />
It accepts a-z and A-Z plus space
listen to keyDown event and match with this regex:
/[a-zA-Z]+/
if you're targeting modern browsers only, you can try this:
<input type="text" pattern="[a-zA-Z]" title="Only letters" />
you can't avoid that the user types non alphabetic characters. But you can:
- control the input fields (onkeydown) and check if there are some characters you don't want Stackoverflow - force input to only alpha-letters
- do the same before the
label.textContent = candidateNameInputs[index].value;
line and filter/replace the characters you don't want
var val = document.getElementById('id').value;
if (!val.match(/^[a-zA-Z]+$/))
{
alert('Only alphabets are allowed');
return false;
}
full script
function EnterCandidates() {
console.log('woo');
var candidateNameInputs = document.querySelectorAll('input[id^=C]'),
names = document.querySelectorAll('label[for^=V][id^=L_V]');
Array.prototype.forEach.call(names, function (label, index) {
if (!candidateNameInputs[index].value.match(/^[a-zA-Z]+$/))
{
alert('Only alphabets are allowed');
}
else
{
if (candidateNameInputs[index].value !== candidateNameInputs[index].defaultValue) {
label.textContent = candidateNameInputs[index].value;
}
}
});
}
Here is one way to do it using Javascript.
http://jsfiddle.net/q60gm0ra/
var input = document.getElementById('alpha');
input.addEventListener('keypress',function(e) {
var str = String.fromCharCode(e.charCode);
if (!(/[A-Z]|\s/i).test(str)) {
e.preventDefault();
}
});

Categories

Resources