I have a basic form validation right now in Javascript right now. How do I format it so that whatever is typed in the input field MUST be:
- Uppercase
- No spaces
- No more than 5 characters
- None of the following special symbols: !@#$%^&*()-_ =][{}|’”:;?/><,~`
- No numbers
Javascript:
function stockValidate() {
let x = document.getElementById("inputText3").value;
let text;
if FORMATTING HERE {
text = "Input not valid";
document.getElementById("inputText3").value = '';
} else {
text = "Input OK";
}
document.getElementById("demo").innerHTML = text;
}
HTML:
<div >
<input type="text" id="inputText3" aria-describedby="TextHelpInline" placeholder="e.g. AAPL"/>
</div>
<div >
<button id="inputTextBtn3" onclick="stockValidate()">Add</button>
</div>
<p id="demo"></p>
CodePudding user response:
I would try that way of solving the issue:
Add validation only for capital letter and numbers
Since you included your html code I would even call the way using the pattern-attribute the simple way to do this validation.
PS: https://www.w3schools.com/tags/att_input_pattern.asp
CodePudding user response:
As per @Graficode's tips, here is the final code:
function stockValidate() {
var specialChars = /[`!@#$%^&*()_ \-=\[\]{};':"\\|,<>\/?~]/;
let x = document.getElementById("inputText3").value;
let text;
if (x.toUpperCase() != x) {
document.getElementById('demo').style.display = "block";
text = "Stock symbol must be uppercase";
document.getElementById("inputText3").value = '';
}
else if (x === '') {
document.getElementById('demo').style.display = "block";
text = "No blanks"
}
else if (x.includes(' ')) {
text = "No spaces";
document.getElementById('demo').style.display = "block";
document.getElementById("inputText3").value = '';
}
else if (x.length > 5) {
document.getElementById('demo').style.display = "block";
text = "No more than 5 characters";
document.getElementById("inputText3").value = '';
}
else if (/\d/.test(x)) {
document.getElementById('demo').style.display = "block";
text = "No numbers allowed";
document.getElementById("inputText3").value = '';
}
else if (specialChars.test(x)) {
document.getElementById('demo').style.display = "block";
text = "No special characters allowed";
document.getElementById("inputText3").value = '';
}
else {
text = "Input OK";
document.getElementById('demo').style.display = "none";
}
document.getElementById("demo").innerHTML = text;
}