Reputation: 61
I am a beginner with CoffeeScript doing my first html validation. I can't get my html form validated. The code goes like this:
<script type="text/coffeescript">
usernameValidate = ->
x = document.getElementById("username").value
ptrn = /^[A-z0-9]{5,8}$/
if ptrn.test(x)
document.getElementById("usrmsg").innerHTML = ""
barwidth = barwidth + 10
document.getElementById("progress").style.width = barwidth + "%"
return true
else
y = "Only Alpha Numeric and Length between 5-8 chars"
document.getElementById("usrmsg").innerHTML = "<img src='./icons/error.png'>" + y
document.getElementById("progress").style.width = barwidth + "%"
document.getElementById("username").focus()
return false
barwidth = 0
</script>
<script type="text/javascript" src="js/coffee-script.js"></script>
and the html:
<input type="text" name="uname" placeholder="User Name" id="username" onblur="usernameValidate()">
<span id="usrmsg"></span>
<div class="progress progress-striped active" id="progressbar">
<div class="bar" id="progress"></div>
</div>
I have used twitter bootstrap for progress bar. I want - The progress bar to increase in width for valid username - Error msg should displayed if input is not a valid pattern
Please suggest where I went wrong. I thank you in advance
Upvotes: 2
Views: 909
Reputation: 434685
First fix your indentation so that you have valid CoffeeScript:
usernameValidate = ->
x = document.getElementById("username").value
ptrn = /^[A-z0-9]{5,8}$/
if ptrn.test(x)
document.getElementById("usrmsg").innerHTML = ""
barwidth = barwidth + 10
document.getElementById("progress").style.width = barwidth + "%"
return true
else
y = "Only Alpha Numeric and Length between 5-8 chars"
document.getElementById("usrmsg").innerHTML = "<img src='./icons/error.png'>" + y
document.getElementById("progress").style.width = barwidth + "%"
document.getElementById("username").focus()
return false
barwidth = 0
I'd move barwidth
to the top but it shouldn't matter as the variable will be hoisted to the top anyway and it will be initialized before usernameValidate
runs.
I see two other possible problems:
<input>
has been seen.<script type="text/coffeescript">
probably wraps everything in a self execute function wrapper just like the usual coffee
command does.The second one can be fixed by forcing your function into the global namespace:
@usernameValidate = -> ...
# or
window.usernameValidate = -> ...
@
(AKA this
) in this context should be window
so you should be able to use @usernameValidate
.
Solving the first one is a bit more work. Your best bet here would be to stop pretending that it is 1995 and abandon the onblur
attribute in favor of addEventListener
or a library that does that for you. If you go this route then 2 goes away as you can bind your event handler without having to pollute the global namespace.
Upvotes: 1