Last active
August 12, 2022 04:47
-
-
Save RileySeaburg/0c8b0297c8d332c927e3e69b055ddece to your computer and use it in GitHub Desktop.
Validate User Input Using Streams in Dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<form> | |
<h4>Guess the Word<h4> | |
<input/> | |
<button>Guess</button> | |
<div id="error" ></div> | |
</form> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
h4 { | |
color: white; | |
} | |
form{ | |
display: flex; | |
flex-direction: column; | |
} | |
#error { | |
color: red; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:html'; | |
import 'dart:async'; | |
void main() { | |
final InputElement input = querySelector("input") as InputElement; | |
final DivElement div = querySelector('#error') as DivElement; | |
/// Create Stream Transformer Object | |
final validateEmail = | |
StreamTransformer.fromHandlers(handleData: (inputValue, sink) { | |
if (inputValue.toString().contains('@')) { | |
sink.add(inputValue); | |
} else { | |
sink.addError('Enter a valid email address'); | |
} | |
}); | |
final validateDomain = | |
StreamTransformer.fromHandlers(handleData: (inputValue, sink) { | |
if (inputValue.toString().contains('.com')) { | |
sink.add(inputValue); | |
} else { | |
sink.addError('Enter a valid email address'); | |
} | |
}); | |
/// Dynamically Print User Input | |
input.onInput | |
.map((dynamic event) => event.target.value) | |
.transform(validateEmail) | |
.transform(validateDomain) | |
.listen((inputValue) => div.innerHtml = '', | |
onError: (err) => div.innerHtml = err); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment