Reputation: 41
I am trying for our contact page to allow submission only once a correct phrase is entered. I have no idea how and tried the alert function. It alerts when the wrong phrase is entered, but still submits the form. Basically I am trying to prevent automated submission of our form.
The relevant code:
**HTML:**
<label for="phrase" class="p">Please enter "security" below</label><br>
<input type="text" id="phrase" name="phrase" required></type><br>
<input type="submit"; onclick="no_spam()"; value="Submit"></type>
**JS:**
function no_spam() {
var spam = document.getElementById("phrase").value;
if(spam !== "security")
{alert("Enter correct phrase")}
}
Upvotes: 2
Views: 31
Reputation: 35096
Because you are talking about submitting, I assume you also have a FORM tag.
<form action=...>
<input name=.... />
</form>
#1. Don't use onXXX event registration. This is a dangerous hackable feature in HTML/Javascript, one that is disallowed if you use a Content-Security-Policy. Instead, use
document.getElementById("myForm").addEventListener("submit", function(e) {
//validate your form. If not valid, call e.preventDefault();
});
The other thing you can do (assuming you are working in HTML 5) is use the pattern
attribute to create a regex to make sure the input is valid. Using this attribute, the form will not submit if the field doesn't pass validation
Upvotes: 1
Reputation: 4922
You don't need any JavaScript; it can be done entirely in HTML5 using the pattern
attribute.
<form>
<label for="phrase" class="p">Please enter "security" below</label><br>
<input type="text" id="phrase" name="phrase" required pattern="^security$" title="Enter correct phrase"></type><br>
<input type="submit" value="Submit"></type>
</form>
Upvotes: 1